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/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/FileTransformerConfigurationTest.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.core; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.core.FileTransformerConfiguration.FailureBehavior.DELETE; import static software.amazon.awssdk.core.FileTransformerConfiguration.FileWriteOption.CREATE_NEW; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class FileTransformerConfigurationTest { @Test void equalsHashcode() { EqualsVerifier.forClass(FileTransformerConfiguration.class) .withNonnullFields("fileWriteOption", "failureBehavior") .verify(); } @Test void toBuilder() { FileTransformerConfiguration configuration = FileTransformerConfiguration.builder() .failureBehavior(DELETE) .fileWriteOption(CREATE_NEW) .build(); FileTransformerConfiguration another = configuration.toBuilder().build(); assertThat(configuration).isEqualTo(another); } }
1,600
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/SdkNumberTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Objects; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.EnabledOnJre; import org.junit.jupiter.api.condition.JRE; public class SdkNumberTest { public static final String THIRTY_TWO_DIGITS = "100000000000000000000000000000000"; @Test public void integerSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromInteger(-100); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-100)); assertThat(sdkNumber.longValue()).isEqualTo(-100L); assertThat(sdkNumber.doubleValue()).isEqualTo(-100.0); assertThat(sdkNumber.floatValue()).isEqualTo(-100.0f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -100); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -100); assertThat(sdkNumber).hasToString("-100"); assertThat(SdkNumber.fromInteger(-100)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromInteger(-100))); } @Test public void longSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromLong(-123456789L); assertThat(sdkNumber.longValue()).isEqualTo(-123456789L); assertThat(sdkNumber.intValue()).isEqualTo(-123456789); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.0); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.0f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789); assertThat(sdkNumber).hasToString("-123456789"); assertThat(SdkNumber.fromLong(-123456789L)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromLong(-123456789L))); } @Test public void doubleSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromDouble(-123456789.987654321); assertThat(sdkNumber.longValue()).isEqualTo(-123456789L); assertThat(sdkNumber.intValue()).isEqualTo(-123456789); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789.987654321)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.987654321); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789); assertThat(sdkNumber).hasToString("-1.2345678998765433E8"); assertThat(SdkNumber.fromDouble(-123456789.987654321)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromDouble(-123456789.987654321))); } @Test public void shortSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromShort((short) 2); assertThat(sdkNumber.longValue()).isEqualTo(2L); assertThat(sdkNumber.doubleValue()).isEqualTo(2); assertThat(sdkNumber.floatValue()).isEqualTo(2); assertThat(sdkNumber.shortValue()).isEqualTo((short) 2); assertThat(sdkNumber.byteValue()).isEqualTo((byte) 2); assertThat(sdkNumber).hasToString("2"); } @Test public void floatSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.longValue()).isEqualTo((long) -123456789.987654321f); assertThat(sdkNumber.intValue()).isEqualTo((int) -123456789.987654321f); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789.987654321f)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789.987654321f); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789.987654321f); } // JDK 19+ changes the float formatting: https://bugs.openjdk.org/browse/JDK-8300869 @Test @EnabledForJreRange(max = JRE.JAVA_18) public void floatSdkNumber_lt_jdk19() { SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.toString()).isEqualTo("-1.23456792E8") .isEqualTo(Float.valueOf(-123456789.987654321f).toString()); } // JDK 19+ changes the float formatting: https://bugs.openjdk.org/browse/JDK-8300869 @Test @EnabledForJreRange(min = JRE.JAVA_19) public void floatSdkNumber_gt_jdk19() { SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.toString()).isEqualTo("-1.2345679E8") .isEqualTo(Float.valueOf(-123456789.987654321f).toString()); } @Test public void bigDecimalSdkNumber() { final BigDecimal bigDecimalValue = new BigDecimal(-123456789.987654321); final SdkNumber sdkNumber = SdkNumber.fromBigDecimal(bigDecimalValue); assertThat(sdkNumber.longValue()).isEqualTo(bigDecimalValue.longValue()); assertThat(sdkNumber.intValue()).isEqualTo(bigDecimalValue.intValue()); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(new BigDecimal(-123456789.987654321)); assertThat(sdkNumber.doubleValue()).isEqualByComparingTo(-123456789.987654321); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo(bigDecimalValue.shortValue()); assertThat(sdkNumber.byteValue()).isEqualTo(bigDecimalValue.byteValue()); assertThat(sdkNumber).hasToString(bigDecimalValue.toString()); assertThat(SdkNumber.fromBigDecimal(new BigDecimal(-123456789.987654321))).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromBigDecimal(new BigDecimal(-123456789.987654321)))); } @Test public void numberFromString() { final SdkNumber sdkSmallNumber = SdkNumber.fromString("1"); assertThat(sdkSmallNumber.longValue()).isEqualTo(1L); assertThat(sdkSmallNumber.stringValue()).isEqualTo("1"); assertThat(sdkSmallNumber.bigDecimalValue()).isEqualTo(new BigDecimal(1)); assertThat(sdkSmallNumber.shortValue()).isEqualTo((short) 1); assertThat(sdkSmallNumber.intValue()).isEqualTo(1); final SdkNumber sdkBigDecimalNumber = SdkNumber.fromString(THIRTY_TWO_DIGITS + ".123456789000000"); final BigDecimal bigDecimal = new BigDecimal(THIRTY_TWO_DIGITS + ".123456789000000"); assertThat(sdkBigDecimalNumber.bigDecimalValue()).isEqualTo(bigDecimal); assertThat(sdkBigDecimalNumber.longValue()).isEqualTo(bigDecimal.longValue()); assertThat(sdkBigDecimalNumber.bigDecimalValue()).isEqualTo(bigDecimal); assertThat(sdkBigDecimalNumber.intValue()).isEqualTo(bigDecimal.intValue()); assertThat(sdkBigDecimalNumber.shortValue()).isEqualTo(bigDecimal.shortValue()); assertThat(sdkBigDecimalNumber.intValue()).isEqualTo(bigDecimal.intValue()); assertThat(sdkBigDecimalNumber.doubleValue()).isEqualTo(bigDecimal.doubleValue()); assertThat(SdkNumber.fromString("1")).isEqualTo(sdkSmallNumber); assertThat(Objects.hashCode(sdkSmallNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromString("1"))); assertThat(sdkBigDecimalNumber).isEqualTo(SdkNumber.fromBigDecimal(bigDecimal)); assertThat(Objects.hashCode(sdkBigDecimalNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromBigDecimal(bigDecimal))); assertThat(sdkBigDecimalNumber.equals(sdkBigDecimalNumber)).isTrue(); } @Test public void numberFromNaNDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.NaN); final Double nanDouble = Double.NaN; assertThat(nanDouble.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, nanDouble); } @Test public void numberFromNaNFloat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.NaN); final Float floatNan = Float.NaN; assertThat(floatNan.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, floatNan); } @Test public void numberFromPositiveInfinityDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.POSITIVE_INFINITY); final Double positiveInfinity = Double.POSITIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } @Test public void numberFromNegativeInfinityDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.NEGATIVE_INFINITY); final Double positiveInfinity = Double.NEGATIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } public void numberFromPositiveInfinityFloat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.POSITIVE_INFINITY); final Float positiveInfinity = Float.POSITIVE_INFINITY; assertThat(positiveInfinity.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } @Test public void numberFromNegativeInfinityFLoat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.NEGATIVE_INFINITY); final Float positiveInfinity = Float.NEGATIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } private void assertEqualitySDKNumberWithNumber(SdkNumber sdkNan, Number nanDouble) { assertThat(sdkNan.longValue()).isEqualTo(nanDouble.longValue()); assertThat(sdkNan.stringValue()).isEqualTo(nanDouble.toString()); assertThat(sdkNan.shortValue()).isEqualTo(nanDouble.shortValue()); assertThat(sdkNan.intValue()).isEqualTo(nanDouble.intValue()); assertThat(sdkNan).hasToString(nanDouble.toString()); assertThat(sdkNan.byteValue()).isEqualTo(nanDouble.byteValue()); // convert to nullable Double to prevent comparison of primitives because Double.NaN == Double.NaN is false assertThat(Double.valueOf(sdkNan.doubleValue())).isEqualTo(Double.valueOf(nanDouble.doubleValue())); assertThat(sdkNan.byteValue()).isEqualTo(nanDouble.byteValue()); } @Test public void bigIntegerNumber() { final SdkNumber sdkNumber = SdkNumber.fromBigInteger(new BigInteger(THIRTY_TWO_DIGITS)); BigInteger bigIntegerExpected = new BigInteger(THIRTY_TWO_DIGITS); assertEqualitySDKNumberWithNumber(sdkNumber, bigIntegerExpected); } @Test public void sdkNumberNotEqualToPrimitive(){ assertThat(SdkNumber.fromInteger(2)).isNotEqualTo(2); } }
1,601
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/RequestOverrideConfigurationTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.utils.ImmutableMap; public class RequestOverrideConfigurationTest { private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>(); private static ExecutionAttribute<Object> attr(String name) { name = RequestOverrideConfigurationTest.class.getName() + ":" + name; return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new); } private static final String HEADER = "header"; private static final String QUERY_PARAM = "queryparam"; @Test public void equalsHashcode() { EqualsVerifier.forClass(RequestOverrideConfiguration.class) .usingGetClass() .verify(); } @Test public void toBuilder_minimal() { RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .build(); assertThat(configuration.toBuilder().build()).usingRecursiveComparison().isEqualTo(configuration); } @Test public void toBuilder_maximal() { ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "foo") .putRawQueryParameter(QUERY_PARAM, "foo") .addApiName(a -> a.name("test1").version("1")) .apiCallTimeout(Duration.ofSeconds(1)) .apiCallAttemptTimeout(Duration.ofSeconds(1)) .signer(new NoOpSigner()) .executionAttributes(ExecutionAttributes.builder().put(testAttribute, expectedValue).build()) .addMetricPublisher(mock(MetricPublisher.class)) .build(); assertThat(configuration.toBuilder().build()).usingRecursiveComparison().isEqualTo(configuration); } @Test public void addingSameItemTwice_shouldOverride() { RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "foo") .putHeader(HEADER, "bar") .putRawQueryParameter(QUERY_PARAM, "foo") .putRawQueryParameter(QUERY_PARAM, "bar") .addApiName(a -> a.name("test1").version("1")) .addApiName(a -> a.name("test2").version("2")) .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("bar"); assertThat(configuration.rawQueryParameters().get(QUERY_PARAM)).containsExactly("bar"); assertThat(configuration.apiNames().size()).isEqualTo(2); } @Test public void settingCollection_shouldOverrideAddItem() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); ImmutableMap<String, List<String>> queryMap = ImmutableMap.of(QUERY_PARAM, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "blah") .headers(map) .putRawQueryParameter(QUERY_PARAM, "blah") .rawQueryParameters(queryMap) .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("hello", "world"); assertThat(configuration.rawQueryParameters().get(QUERY_PARAM)).containsExactly("hello", "world"); } @Test public void addSameItemAfterSetCollection_shouldOverride() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .headers(map) .putHeader(HEADER, "blah") .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("blah"); } @Test public void shouldGuaranteeImmutability() { List<String> headerValues = new ArrayList<>(); headerValues.add("bar"); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", headerValues); SdkRequestOverrideConfiguration.Builder configurationBuilder = SdkRequestOverrideConfiguration.builder().headers(headers); headerValues.add("test"); headers.put("new header", Collections.singletonList("new value")); assertThat(configurationBuilder.headers().size()).isEqualTo(1); assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar"); } @Test public void metricPublishers_createsCopy() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); List<MetricPublisher> toModify = new ArrayList<>(publishers); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .metricPublishers(toModify) .build(); toModify.clear(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_maintainsAllAdded() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); publishers.forEach(builder::addMetricPublisher); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void metricPublishers_overwritesPreviouslyAdded() { MetricPublisher firstAdded = mock(MetricPublisher.class); List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.addMetricPublisher(firstAdded); builder.metricPublishers(publishers); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_listPreviouslyAdded_appendedToList() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); MetricPublisher thirdAdded = mock(MetricPublisher.class); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.metricPublishers(publishers); builder.addMetricPublisher(thirdAdded); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded); } @Test public void executionAttributes_createsCopy() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); executionAttributes.putAttribute(testAttribute, "Value2"); assertThat(overrideConfig.executionAttributes().getAttribute(testAttribute)).isEqualTo(expectedValue); } @Test public void executionAttributes_isImmutable() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); try { overrideConfig.executionAttributes().putAttribute(testAttribute, 2); fail("Expected unsupported operation exception"); } catch(Exception ex) { assertThat(ex instanceof UnsupportedOperationException).isTrue(); } try { overrideConfig.executionAttributes().putAttributeIfAbsent(testAttribute, 2); fail("Expected unsupported operation exception"); } catch(Exception ex) { assertThat(ex instanceof UnsupportedOperationException).isTrue(); } } @Test public void executionAttributes_maintainsAllAdded() { Map<ExecutionAttribute, Object> executionAttributeObjectMap = new HashMap<>(); for (int i = 0; i < 5; i++) { executionAttributeObjectMap.put(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); for (Map.Entry<ExecutionAttribute, Object> attributeObjectEntry : executionAttributeObjectMap.entrySet()) { builder.putExecutionAttribute(attributeObjectEntry.getKey(), attributeObjectEntry.getValue()); } SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributeObjectMap); } @Test public void executionAttributes_overwritesPreviouslyAdded() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.putExecutionAttribute(attr("AddedAttribute"), mock(Object.class)); builder.executionAttributes(executionAttributes); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes()); } @Test public void executionAttributes_listPreviouslyAdded_appendedToList() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.executionAttributes(executionAttributes); ExecutionAttribute addedAttribute = attr("AddedAttribute"); Object addedValue = mock(Object.class); builder.putExecutionAttribute(addedAttribute, addedValue); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttribute(addedAttribute)).isEqualTo(addedValue); } @Test public void testConfigurationEquals() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration request1Override = SdkRequestOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(1)) .executionAttributes(executionAttributes) .build(); SdkRequestOverrideConfiguration request2Override = SdkRequestOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(1)) .executionAttributes(executionAttributes) .build(); assertThat(request1Override).isEqualTo(request1Override); assertThat(request1Override).isEqualTo(request2Override); assertThat(request1Override).isNotEqualTo(null); } private static class NoOpSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { return null; } } }
1,602
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/CredentialTypeTest.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.core; import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class CredentialTypeTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(CredentialType.class) .withNonnullFields("value") .verify(); } @Test public void credentialType_bearerToken(){ CredentialType token = CredentialType.TOKEN; CredentialType tokenFromString = CredentialType.of("TOKEN"); assertThat(token).isSameAs(tokenFromString); assertThat(token).isEqualTo(tokenFromString); } @Test public void credentialType_usesSameInstance_when_sameCredentialTypeOfSameValue(){ CredentialType credentialTypeOne = CredentialType.of("Credential Type 1"); CredentialType credentialTypeOneDuplicate = CredentialType.of("Credential Type 1"); assertThat(credentialTypeOneDuplicate).isSameAs(credentialTypeOne); assertThat(credentialTypeOne).isEqualTo(credentialTypeOneDuplicate); } }
1,603
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/CompressionConfigurationTest.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.core; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class CompressionConfigurationTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(CompressionConfiguration.class) .withNonnullFields("requestCompressionEnabled", "minimumCompressionThresholdInBytes") .verify(); } @Test public void toBuilder() { CompressionConfiguration configuration = CompressionConfiguration.builder() .requestCompressionEnabled(true) .minimumCompressionThresholdInBytes(99999) .build(); CompressionConfiguration another = configuration.toBuilder().build(); assertThat(configuration).isEqualTo(another); } }
1,604
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/FileRequestBodyConfigurationTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Paths; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class FileRequestBodyConfigurationTest { @Test void equalsHashCode() { EqualsVerifier.forClass(FileRequestBodyConfiguration.class) .verify(); } @Test void invalidRequest_shouldThrowException() { assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .position(-1L) .build()) .hasMessage("position must not be negative"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .numBytesToRead(-1L) .build()) .hasMessage("numBytesToRead must not be negative"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .chunkSizeInBytes(0) .build()) .hasMessage("chunkSizeInBytes must be positive"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .chunkSizeInBytes(-5) .build()) .hasMessage("chunkSizeInBytes must be positive"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .build()) .hasMessage("path"); } @Test void toBuilder_shouldCopyAllProperties() { FileRequestBodyConfiguration config = FileRequestBodyConfiguration.builder() .path(Paths.get(".")).numBytesToRead(100L) .position(1L) .chunkSizeInBytes(1024) .build(); assertThat(config.toBuilder().build()).isEqualTo(config); } }
1,605
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination/PaginatedItemsIterableTest.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.core.pagination; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Iterator; import java.util.function.Function; import org.junit.Before; 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.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.SdkIterable; @RunWith(MockitoJUnitRunner.class) public class PaginatedItemsIterableTest { @Mock private SdkIterable pagesIterable; @Mock private Iterator pagesIterator; @Mock private Function getItemIteratorFunction; @Mock private Iterator singlePageItemsIterator; private PaginatedItemsIterable itemsIterable; @Before public void setup() { when(pagesIterable.iterator()).thenReturn(pagesIterator); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); itemsIterable = PaginatedItemsIterable.builder() .pagesIterable(pagesIterable) .itemIteratorFunction(getItemIteratorFunction) .build(); } @Test public void hasNext_ReturnsFalse_WhenItemsAndPagesIteratorHasNoNextElement() { when(pagesIterator.hasNext()).thenReturn(false); assertFalse(itemsIterable.iterator().hasNext()); } @Test public void hasNext_ReturnsTrue_WhenItemsIteratorHasNextElement() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(true); assertTrue(itemsIterable.iterator().hasNext()); } @Test public void hasNextMethodDoesNotRetrieveNextPage_WhenItemsIteratorHasAnElement() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(true); Iterator itemsIterator = itemsIterable.iterator(); itemsIterator.hasNext(); itemsIterator.hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Not called again in ItemsIterator.hasNext() method verify(pagesIterator, times(1)).next(); } @Test public void hasNextMethodGetsNextPage_WhenCurrentItemsIteratorHasNoElements() { when(pagesIterator.hasNext()).thenReturn(true); when(singlePageItemsIterator.hasNext()).thenReturn(false) .thenReturn(true); itemsIterable.iterator().hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Called second time in hasNext() method verify(pagesIterator, times(2)).next(); } @Test public void hasNextMethodGetsNextPage_WhenCurrentItemsIteratorIsEmpty() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(false, true); itemsIterable.iterator().hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Called second time in hasNext() method verify(pagesIterator, times(2)).next(); } @Test public void testNextMethod_WhenIntermediatePages_HasEmptyCollectionOfItems() { when(pagesIterator.hasNext()).thenReturn(true); // first page has empty items iterator Iterator itemsIterator1 = Mockito.mock(Iterator.class); when(itemsIterator1.hasNext()).thenReturn(false); // second page has empty items iterator Iterator itemsIterator2 = Mockito.mock(Iterator.class); when(itemsIterator2.hasNext()).thenReturn(false); // third page has empty items iterator Iterator itemsIterator3 = Mockito.mock(Iterator.class); when(itemsIterator3.hasNext()).thenReturn(false); // fourth page is non empty Iterator itemsIterator4 = Mockito.mock(Iterator.class); when(itemsIterator4.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(itemsIterator1, itemsIterator2, itemsIterator3, itemsIterator4); itemsIterable.iterator().next(); verify(itemsIterator1, times(0)).next(); verify(itemsIterator2, times(0)).next(); verify(itemsIterator3, times(0)).next(); verify(itemsIterator4, times(1)).next(); verify(getItemIteratorFunction, times(4)).apply(any()); } }
1,606
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination/async/PaginatedItemsPublisherTckTest.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.core.pagination.async; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; /** * TCK verification test for {@link PaginatedItemsPublisher}. */ public class PaginatedItemsPublisherTckTest extends PublisherVerification<Long> { public PaginatedItemsPublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<Long> createPublisher(long l) { Function<List<Long>, Iterator<Long>> getIterator = response -> response != null ? response.iterator() : Collections.emptyIterator(); return PaginatedItemsPublisher.builder() .nextPageFetcher(new PageFetcher(l, 5)) .iteratorFunction(getIterator) .isLastPage(false) .build(); } @Override public Publisher<Long> createFailedPublisher() { // It's not possible to initialize PaginatedItemsPublisher to a failed // state since we can only reach a failed state if we fail to fulfill a // request, e.g. because the service returned an error response. // return null to skip related tests return null; } /** * Simple {@link AsyncPageFetcher} that returns lists of longs as pages. */ private static class PageFetcher implements AsyncPageFetcher<List<Long>> { private final long maxVal; private final long step; private PageFetcher(long maxVal, long step) { this.maxVal = maxVal; this.step = step; } @Override public boolean hasNextPage(List<Long> oldPage) { return (lastElement(oldPage)) < maxVal - 1; } @Override public CompletableFuture<List<Long>> nextPage(List<Long> oldPage) { long i = lastElement(oldPage) + 1; long j = Math.min(i + step, maxVal); List<Long> stream = LongStream.range(i, j).boxed().collect(Collectors.toList()); return CompletableFuture.completedFuture(stream); } private long lastElement(List<Long> s) { // first page is always null if (s == null) return -1; return s.get(s.size() - 1); } } }
1,607
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/AndRetryConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import org.junit.Before; 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.core.retry.conditions.AndRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class AndRetryConditionTest { @Mock private RetryCondition conditionOne; @Mock private RetryCondition conditionTwo; private RetryCondition andCondition; @Before public void setup() { andCondition = AndRetryCondition.create(conditionOne, conditionTwo); } @Test public void allFalseConditions_ReturnsFalse() { assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void onlyFirstConditionIsTrue_ReturnsFalse() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void onlySecondConditionIsTrue_ReturnsFalse() { assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void bothConditionsAreTrue_ReturnsTrue() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); when(conditionTwo.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } /** * The expected result for an AND condition with no conditions is a little unclear so we disallow it until there is a use * case. */ @Test(expected = IllegalArgumentException.class) public void noConditions_ThrowsException() { AndRetryCondition.create().shouldRetry(RetryPolicyContexts.EMPTY); } @Test public void singleConditionThatReturnsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(true); assertTrue(AndRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsFalse_ReturnsFalse() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(false); assertFalse(AndRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void conditionsAreEvaluatedInOrder() { int numConditions = 1000; int firstFalseCondition = 500; RetryCondition[] conditions = new RetryCondition[numConditions]; for (int i = 0; i < numConditions; ++i) { RetryCondition mock = Mockito.mock(RetryCondition.class); when(mock.shouldRetry(RetryPolicyContexts.EMPTY)).thenReturn(i != firstFalseCondition); conditions[i] = mock; } assertFalse(AndRetryCondition.create(conditions).shouldRetry(RetryPolicyContexts.EMPTY)); for (int i = 0; i < numConditions; ++i) { int timesExpected = i <= firstFalseCondition ? 1 : 0; Mockito.verify(conditions[i], times(timesExpected)).shouldRetry(RetryPolicyContexts.EMPTY); } } }
1,608
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/FixedTimeBackoffStrategy.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.core.retry; import java.time.Duration; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; /** * Test implementation of {@link BackoffStrategy} to wait a fixed time between retries */ public class FixedTimeBackoffStrategy implements BackoffStrategy { private final Duration fixedTimeDelay; public FixedTimeBackoffStrategy(Duration fixedTimeDelay) { this.fixedTimeDelay = fixedTimeDelay; } @Override public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) { return this.fixedTimeDelay; } }
1,609
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryModeTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class RetryModeTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, RetryMode.LEGACY), new TestData(null, null, "PropertyNotSet", null, RetryMode.LEGACY), // Test resolution new TestData("legacy", null, null, null, RetryMode.LEGACY), new TestData("standard", null, null, null, RetryMode.STANDARD), new TestData("adaptive", null, null, null, RetryMode.ADAPTIVE), new TestData("lEgAcY", null, null, null, RetryMode.LEGACY), new TestData("sTanDaRd", null, null, null, RetryMode.STANDARD), new TestData("aDaPtIvE", null, null, null, RetryMode.ADAPTIVE), // Test precedence new TestData("standard", "legacy", "PropertySetToLegacy", RetryMode.LEGACY, RetryMode.STANDARD), new TestData("standard", null, null, RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, "standard", "PropertySetToLegacy", RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, "standard", null, RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, null, "PropertySetToStandard", RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, null, null, RetryMode.STANDARD, RetryMode.STANDARD), // Test invalid values new TestData("wrongValue", null, null, null, IllegalStateException.class), new TestData(null, "wrongValue", null, null, IllegalStateException.class), new TestData(null, null, "PropertySetToUnsupportedValue", null, IllegalStateException.class), // Test capitalization standardization new TestData("sTaNdArD", null, null, null, RetryMode.STANDARD), new TestData(null, "sTaNdArD", null, null, RetryMode.STANDARD), new TestData(null, null, "PropertyMixedCase", null, RetryMode.STANDARD), }); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_RETRY_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_RETRY_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } Callable<RetryMode> result = RetryMode.resolver().defaultRetryMode(testData.defaultMode)::resolve; if (testData.expected instanceof Class<?>) { Class<?> expectedClassType = (Class<?>) testData.expected; assertThatThrownBy(result::call).isInstanceOf(expectedClassType); } else { assertThat(result.call()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String envVarValue; private final String systemProperty; private final String configFile; private final RetryMode defaultMode; private final Object expected; TestData(String systemProperty, String envVarValue, String configFile, RetryMode defaultMode, Object expected) { this.envVarValue = envVarValue; this.systemProperty = systemProperty; this.configFile = configFile; this.defaultMode = defaultMode; this.expected = expected; } } }
1,610
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/DefaultRetryConditionTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.conditions.RetryCondition; public class DefaultRetryConditionTest { @Test public void retriesOnThrottlingExceptions() { assertTrue(shouldRetry(applyStatusCode(429))); } @Test public void retriesOnInternalError() { assertTrue(shouldRetry(applyStatusCode(500))); } @Test public void retriesOnBadGateway() { assertTrue(shouldRetry(applyStatusCode(502))); } @Test public void retriesOnServiceUnavailable() { assertTrue(shouldRetry(applyStatusCode(503))); } @Test public void retriesOnGatewayTimeout() { assertTrue(shouldRetry(applyStatusCode(504))); } @Test public void retriesOnIOException() { assertTrue(shouldRetry(b -> b.exception(SdkClientException.builder().message("IO").cause(new IOException()).build()))); } @Test public void retriesOnRetryableException() { assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().message("this is retryable").build()))); } @Test public void doesNotRetryOnNonRetryableException() { assertFalse(shouldRetry(b -> b.exception(NonRetryableException.builder().message("this is NOT retryable").build()))); } @Test public void doesNotRetryOnNonRetryableStatusCode() { assertFalse(shouldRetry(applyStatusCode(404))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return RetryCondition.defaultRetryCondition().shouldRetry(RetryPolicyContext.builder() .applyMutation(builder) .build()); } private Consumer<RetryPolicyContext.Builder> applyStatusCode(Integer statusCode) { SdkServiceException exception = SdkServiceException.builder().statusCode(statusCode).build(); return b -> b.exception(exception) .httpStatusCode(statusCode); } }
1,611
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/MaxNumberOfRetriesConditionTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition; public class MaxNumberOfRetriesConditionTest { @Test public void positiveMaxRetries_OneMoreAttemptToMax_ReturnsTrue() { assertTrue(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(2))); } @Test public void positiveMaxRetries_AtMaxAttempts_ReturnsFalse() { assertFalse(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(3))); } @Test public void positiveMaxRetries_PastMaxAttempts_ReturnsFalse() { assertFalse(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(4))); } }
1,612
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/FixedDelayBackoffStrategyTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public class FixedDelayBackoffStrategyTest { @Test public void positiveBackoff_ReturnsFixedBackoffOnDelay() { long delay = FixedDelayBackoffStrategy.create(Duration.ofMillis(100)).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY) .toMillis(); assertEquals(100, delay); } }
1,613
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyMaxRetriesTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class RetryPolicyMaxRetriesTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, null, 3), new TestData(null, null, null, null, "PropertyNotSet", 3), // Test precedence new TestData("9", "2", "standard", "standard", "PropertySetToStandard", 8), new TestData(null, "9", "standard", "standard", "PropertySetToStandard", 8), new TestData(null, null, "standard", "standard", "PropertySetToStandard", 2), new TestData(null, null, null, "standard", "PropertySetToStandard", 2), new TestData(null, null, null, null, "PropertySetToStandard", 2), // Test invalid values new TestData("wrongValue", null, null, null, null, null), new TestData(null, "wrongValue", null, null, null, null), new TestData(null, null, "wrongValue", null, null, null), new TestData(null, null, null, "wrongValue", null, null), new TestData(null, null, null, null, "PropertySetToUnsupportedValue", null), }); } @BeforeClass public static void classSetup() { // If this caches any values, make sure it's cached with the default (non-modified) configuration. RetryPolicy.defaultRetryPolicy(); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_MAX_ATTEMPTS.property()); System.clearProperty(SdkSystemSetting.AWS_RETRY_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() { if (testData.attemptCountEnvVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_MAX_ATTEMPTS.environmentVariable(), testData.attemptCountEnvVarValue); } if (testData.attemptCountSystemProperty != null) { System.setProperty(SdkSystemSetting.AWS_MAX_ATTEMPTS.property(), testData.attemptCountSystemProperty); } if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_RETRY_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } if (testData.expected == null) { assertThatThrownBy(() -> RetryPolicy.forRetryMode(RetryMode.defaultRetryMode())).isInstanceOf(RuntimeException.class); } else { assertThat(RetryPolicy.forRetryMode(RetryMode.defaultRetryMode()).numRetries()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String attemptCountSystemProperty; private final String attemptCountEnvVarValue; private final String envVarValue; private final String systemProperty; private final String configFile; private final Integer expected; TestData(String attemptCountSystemProperty, String attemptCountEnvVarValue, String retryModeSystemProperty, String retryModeEnvVarValue, String configFile, Integer expected) { this.attemptCountSystemProperty = attemptCountSystemProperty; this.attemptCountEnvVarValue = attemptCountEnvVarValue; this.envVarValue = retryModeEnvVarValue; this.systemProperty = retryModeSystemProperty; this.configFile = configFile; this.expected = expected; } } }
1,614
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/OrRetryConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; 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.core.retry.conditions.OrRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class OrRetryConditionTest { @Mock private RetryCondition conditionOne; @Mock private RetryCondition conditionTwo; private RetryCondition orCondition; @Before public void setup() { this.orCondition = OrRetryCondition.create(conditionOne, conditionTwo); } @Test public void allFalseConditions_ReturnsFalse() { assertFalse(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void firstConditionIsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void secondConditionIsTrue_ReturnsTrue() { when(conditionTwo.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void noConditions_ReturnsFalse() { assertFalse(OrRetryCondition.create().shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(true); assertTrue(OrRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsFalse_ReturnsFalse() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(false); assertFalse(OrRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void conditionsAreEvaluatedInOrder() { int numConditions = 1000; int firstTrueCondition = 500; RetryCondition[] conditions = new RetryCondition[numConditions]; for (int i = 0; i < numConditions; ++i) { RetryCondition mock = Mockito.mock(RetryCondition.class); when(mock.shouldRetry(RetryPolicyContexts.EMPTY)).thenReturn(i == firstTrueCondition); conditions[i] = mock; } assertTrue(OrRetryCondition.create(conditions).shouldRetry(RetryPolicyContexts.EMPTY)); for (int i = 0; i < numConditions; ++i) { int timesExpected = i <= firstTrueCondition ? 1 : 0; Mockito.verify(conditions[i], times(timesExpected)).shouldRetry(RetryPolicyContexts.EMPTY); } } }
1,615
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryOnStatusCodeConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Set; import org.junit.Test; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryOnStatusCodeCondition; public class RetryOnStatusCodeConditionTest { private final RetryCondition condition = RetryOnStatusCodeCondition.create(Sets.newHashSet(404, 500, 513)); @Test public void retryableStatusCode_ReturnsTrue() { assertTrue(condition.shouldRetry(RetryPolicyContexts.withStatusCode(404))); } @Test public void nonRetryableStatusCode_ReturnsTrue() { assertFalse(condition.shouldRetry(RetryPolicyContexts.withStatusCode(400))); } @Test public void noStatusCodeInContext_ReturnFalse() { assertFalse(condition.shouldRetry(RetryPolicyContexts.withStatusCode(null))); } @Test public void noStatusCodesInList_ReturnsFalse() { final RetryCondition noStatusCodes = RetryOnStatusCodeCondition.create(Collections.emptySet()); assertFalse(noStatusCodes.shouldRetry(RetryPolicyContexts.withStatusCode(404))); } @Test(expected = NullPointerException.class) public void nullListOfStatusCodes_ThrowsException() { Set<Integer> nullSet = null; RetryOnStatusCodeCondition.create(nullSet); } }
1,616
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyContexts.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.core.retry; import software.amazon.awssdk.core.exception.SdkException; /** * Precanned instances of {@link RetryPolicyContext} and factory methods for creating contexts. */ public class RetryPolicyContexts { /** * Empty context object. */ public static final RetryPolicyContext EMPTY = RetryPolicyContext.builder().build(); public static RetryPolicyContext withException(SdkException e) { return RetryPolicyContext.builder() .exception(e) .build(); } public static RetryPolicyContext withStatusCode(Integer httpStatusCode) { return RetryPolicyContext.builder() .httpStatusCode(httpStatusCode) .build(); } public static RetryPolicyContext withRetriesAttempted(int retriesAttempted) { return RetryPolicyContext.builder() .retriesAttempted(retriesAttempted) .build(); } }
1,617
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyContextTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.ValidSdkObjects; public class RetryPolicyContextTest { @Test public void totalRequests_IsOneMoreThanRetriesAttempted() { assertEquals(4, RetryPolicyContexts.withRetriesAttempted(3).totalRequests()); } @Test public void nullHttpStatusCodeAllowed() { assertNull(RetryPolicyContexts.withStatusCode(null).httpStatusCode()); } @Test public void nullExceptionAllowed() { assertNull(RetryPolicyContexts.withException(null).exception()); } @Test public void buildFully() { final SdkRequest origRequest = NoopTestRequest.builder().build(); final SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); final SdkClientException exception = SdkClientException.builder().message("boom").build(); final RetryPolicyContext context = RetryPolicyContext.builder() .retriesAttempted(3) .httpStatusCode(400) .request(request) .exception(exception) .originalRequest(origRequest) .build(); assertEquals(3, context.retriesAttempted()); assertEquals(Integer.valueOf(400), context.httpStatusCode()); assertEquals(request, context.request()); assertEquals(exception, context.exception()); assertEquals(origRequest, context.originalRequest()); } }
1,618
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; import java.time.Duration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.EqualJitterBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class RetryPolicyTest { @Mock private RetryCondition retryCondition; @Mock private BackoffStrategy backoffStrategy; @Mock private BackoffStrategy throttlingBackoffStrategy; @Test public void nullConditionProvided_useDefault() { RetryPolicy policy = RetryPolicy.builder().build(); RetryPolicy defaultRetryPolicy = RetryPolicy.defaultRetryPolicy(); assertThat(policy).isEqualTo(defaultRetryPolicy); assertThat(policy.retryCondition()).isEqualTo(defaultRetryPolicy.retryCondition()); assertThat(policy.backoffStrategy()).isEqualTo(BackoffStrategy.defaultStrategy()); assertThat(policy.throttlingBackoffStrategy()).isEqualTo(BackoffStrategy.defaultThrottlingStrategy()); } @Test public void shouldRetry_DelegatesToRetryCondition() { RetryPolicy policy = RetryPolicy.builder().retryCondition(retryCondition).backoffStrategy(backoffStrategy).build(); policy.retryCondition().shouldRetry(RetryPolicyContexts.EMPTY); verify(retryCondition).shouldRetry(RetryPolicyContexts.EMPTY); } @Test public void delay_DelegatesToBackoffStrategy() { RetryPolicy policy = RetryPolicy.builder().retryCondition(retryCondition).backoffStrategy(backoffStrategy).build(); policy.backoffStrategy().computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); verify(backoffStrategy).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); } @Test public void throttlingDelay_delegatesToThrottlingBackoffStrategy() { RetryPolicy policy = RetryPolicy.builder().throttlingBackoffStrategy(throttlingBackoffStrategy).build(); policy.throttlingBackoffStrategy().computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); verify(throttlingBackoffStrategy).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); } @Test public void nonRetryPolicy_shouldUseNullCondition() { RetryPolicy noneRetry = RetryPolicy.none(); assertThat(noneRetry.retryCondition().shouldRetry(RetryPolicyContext.builder().build())).isFalse(); assertThat(noneRetry.numRetries()).isZero(); assertThat(noneRetry.backoffStrategy()).isEqualTo(BackoffStrategy.none()); assertThat(noneRetry.throttlingBackoffStrategy()).isEqualTo(BackoffStrategy.none()); } @Test public void nonRetryMode_shouldUseDefaultRetryMode() { RetryPolicy policy = RetryPolicy.builder().build(); assertThat(policy.retryMode().toString()).isEqualTo("LEGACY"); } @Test public void nullRetryMode_shouldThrowNullPointerException() { assertThatThrownBy(() -> RetryPolicy.builder(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("retry mode cannot be set as null"); } @Test public void maxRetriesFromRetryModeIsCorrect() { assertThat(RetryPolicy.forRetryMode(RetryMode.LEGACY).numRetries()).isEqualTo(3); assertThat(RetryPolicy.forRetryMode(RetryMode.STANDARD).numRetries()).isEqualTo(2); } @Test public void maxRetriesFromDefaultRetryModeIsCorrect() { switch (RetryMode.defaultRetryMode()) { case LEGACY: assertThat(RetryPolicy.defaultRetryPolicy().numRetries()).isEqualTo(3); assertThat(RetryPolicy.builder().build().numRetries()).isEqualTo(3); break; case STANDARD: assertThat(RetryPolicy.defaultRetryPolicy().numRetries()).isEqualTo(2); assertThat(RetryPolicy.builder().build().numRetries()).isEqualTo(2); break; default: Assert.fail(); } } @Test public void legacyRetryMode_shouldUseFullJitterAndEqualJitter() { RetryPolicy legacyRetryPolicy = RetryPolicy.forRetryMode(RetryMode.LEGACY); assertThat(legacyRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) legacyRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(legacyRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(EqualJitterBackoffStrategy.class); EqualJitterBackoffStrategy throttlingBackoffStrategy = (EqualJitterBackoffStrategy) legacyRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(500)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void standardRetryMode_shouldUseFullJitterOnly() { RetryPolicy standardRetryPolicy = RetryPolicy.forRetryMode(RetryMode.STANDARD); assertThat(standardRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(standardRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy throttlingBackoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofSeconds(1)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void adaptiveRetryMode_shouldUseFullJitterOnly() { RetryPolicy standardRetryPolicy = RetryPolicy.forRetryMode(RetryMode.ADAPTIVE); assertThat(standardRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(standardRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy throttlingBackoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofSeconds(1)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void fastFailRateLimitingConfigured_retryModeNotAdaptive_throws() { assertThatThrownBy(() -> RetryPolicy.builder(RetryMode.STANDARD).fastFailRateLimiting(true).build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("only valid for the ADAPTIVE retry mode"); } @Test public void fastFailRateLimitingConfigured_retryModeAdaptive_doesNotThrow() { RetryPolicy.builder(RetryMode.ADAPTIVE).fastFailRateLimiting(true).build(); } @Test public void hashCodeDoesNotThrow() { RetryPolicy.defaultRetryPolicy().hashCode(); } }
1,619
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/backoff/FullJitterBackoffStrategyTest.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.core.retry.backoff; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Random; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.mockito.Mock; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicyContext; @RunWith(Parameterized.class) public class FullJitterBackoffStrategyTest { @Parameters public static Collection<TestCase> parameters() throws Exception { return Arrays.asList( new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(0) .expectedMaxDelay(Duration.ofMillis(100)) .expectedMedDelay(Duration.ofMillis(50)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(1) .expectedMaxDelay(Duration.ofMillis(200)) .expectedMedDelay(Duration.ofMillis(100)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(2) .expectedMaxDelay(Duration.ofMillis(400)) .expectedMedDelay(Duration.ofMillis(200)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(3) .expectedMaxDelay(Duration.ofMillis(800)) .expectedMedDelay(Duration.ofMillis(400)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(4) .expectedMaxDelay(Duration.ofMillis(1600)) .expectedMedDelay(Duration.ofMillis(800)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(5) .expectedMaxDelay(Duration.ofMillis(3200)) .expectedMedDelay(Duration.ofMillis(1600)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(100) .expectedMaxDelay(Duration.ofSeconds(20)) .expectedMedDelay(Duration.ofSeconds(10)) .expectedMinDelay(Duration.ofMillis(1)) ); } @Parameter public TestCase testCase; @Mock private Random mockRandom = mock(Random.class, withSettings().withoutAnnotations()); @Before public void setUp() throws Exception { testCase.backoffStrategy = injectMockRandom(testCase.backoffStrategy); } @Test public void testMaxDelay() { mockMaxRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMaxDelay); } @Test public void testMedDelay() { mockMediumRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMedDelay); } @Test public void testMinDelay() { mockMinRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMinDelay); } private static void test(BackoffStrategy backoffStrategy, int retriesAttempted, Duration expectedDelay) { RetryPolicyContext context = RetryPolicyContext.builder() .retriesAttempted(retriesAttempted) .build(); Duration computedDelay = backoffStrategy.computeDelayBeforeNextRetry(context); assertThat(computedDelay).isEqualTo(expectedDelay); } private FullJitterBackoffStrategy injectMockRandom(BackoffStrategy strategy) { FullJitterBackoffStrategy.Builder builder = ((FullJitterBackoffStrategy) strategy).toBuilder(); return new FullJitterBackoffStrategy(builder.baseDelay(), builder.maxBackoffTime(), mockRandom); } private void mockMaxRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { Integer firstArg = (Integer) returnsFirstArg().answer(invocationOnMock); return firstArg - 1; }); } private void mockMinRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { return 0; }); } private void mockMediumRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { Integer firstArg = (Integer) returnsFirstArg().answer(invocationOnMock); return firstArg / 2 - 1; }); } private static class TestCase { private BackoffStrategy backoffStrategy; private int retriesAttempted; private Duration expectedMinDelay; private Duration expectedMedDelay; private Duration expectedMaxDelay; public TestCase backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } public TestCase retriesAttempted(int retriesAttempted) { this.retriesAttempted = retriesAttempted; return this; } public TestCase expectedMinDelay(Duration expectedMinDelay) { this.expectedMinDelay = expectedMinDelay; return this; } public TestCase expectedMedDelay(Duration expectedMedDelay) { this.expectedMedDelay = expectedMedDelay; return this; } public TestCase expectedMaxDelay(Duration expectedMaxDelay) { this.expectedMaxDelay = expectedMaxDelay; return this; } } }
1,620
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/backoff/EqualJitterBackoffStrategyTest.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.core.retry.backoff; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import static org.testng.Assert.assertThrows; import java.time.Duration; import java.util.Random; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockSettings; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class EqualJitterBackoffStrategyTest { private static final int RANDOM_RESULT = 12345; private static final Duration FIVE_DAYS = Duration.ofDays(5); private static final Duration MAX_DURATION = Duration.ofSeconds(Long.MAX_VALUE); private static final Duration ONE_SECOND = Duration.ofSeconds(1); private static final Duration ONE_NANO_SECOND = Duration.ofNanos(1); private static final int NANO_IN_MILLISECONDS = 1_000_000; private static final Duration NEGATIVE_ONE_SECOND = Duration.ofSeconds(-1); @Mock private Random mockRandom = mock(Random.class, withSettings().withoutAnnotations()); @Test public void exponentialDelayOverflowWithMaxBackoffTest() { test(FIVE_DAYS, MAX_DURATION, 3, Integer.MAX_VALUE); } @Test public void exponentialDelayOverflowWithMaxBaseDelayTest() { test(MAX_DURATION, MAX_DURATION, 1, Integer.MAX_VALUE); } @Test public void maxBaseDelayShortBackoffTest() { test(MAX_DURATION, ONE_SECOND, 1, (int) ONE_SECOND.toMillis()); } @Test public void normalConditionTest() { test(ONE_SECOND, MAX_DURATION, 10, (1 << 10) * (int) ONE_SECOND.toMillis()); } @Test public void tinyBackoffNormalRetriesTest() { test(MAX_DURATION, ONE_NANO_SECOND, 10, 0); } @Test public void tinyBaseDelayNormalRetriesTest() { test(ONE_NANO_SECOND, MAX_DURATION, 30, (int) (1L << 30) / NANO_IN_MILLISECONDS); } @Test public void tinyBaseDelayExtraRetriesTest() { test(ONE_NANO_SECOND, MAX_DURATION, 100, (int) (1L << 30) / NANO_IN_MILLISECONDS); // RETRIES_ATTEMPTED_CEILING == 30 } @Test public void exponentialDelayOverflowWithExtraRetriesTest() { test(MAX_DURATION, MAX_DURATION, 100, Integer.MAX_VALUE); } @Test public void tinyBaseDelayUnderflowTest() { test(ONE_NANO_SECOND, MAX_DURATION, 0, 0); } @Test public void negativeBaseDelayTest() { assertThrows(IllegalArgumentException.class, () -> test(NEGATIVE_ONE_SECOND, MAX_DURATION, 1, 0)); } @Test public void negativeBackoffTest() { assertThrows(IllegalArgumentException.class, () -> test(ONE_SECOND, NEGATIVE_ONE_SECOND, 1, 0)); } private void test(final Duration baseDelay, final Duration maxBackoffTime, final int retriesAttempted, final int expectedCeilingMillis) { final BackoffStrategy backoffStrategy = new EqualJitterBackoffStrategy(baseDelay, maxBackoffTime, mockRandom); when(mockRandom.nextInt(expectedCeilingMillis /2 + 1)).thenReturn(RANDOM_RESULT); assertThat(backoffStrategy.computeDelayBeforeNextRetry(toRetryContext(retriesAttempted)), is(Duration.ofMillis(expectedCeilingMillis / 2 + RANDOM_RESULT))); } private static RetryPolicyContext toRetryContext(final int retriesAttempted) { return RetryPolicyContext.builder().retriesAttempted(retriesAttempted).build(); } }
1,621
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/conditions/TokenBucketRetryConditionTest.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.core.retry.conditions; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class TokenBucketRetryConditionTest { private static final SdkException EXCEPTION = SdkClientException.create(""); private static final SdkException EXCEPTION_2 = SdkClientException.create(""); @Test public void maximumTokensCannotBeExceeded() { TokenBucketRetryCondition condition = create(3, e -> 1); for (int i = 1; i < 10; ++i) { condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(3); } } @Test public void releasingMoreCapacityThanAvailableSetsCapacityToMax() { ExecutionAttributes attributes = new ExecutionAttributes(); TokenBucketRetryCondition condition = create(11, e -> e == EXCEPTION ? 1 : 3); assertThat(condition.shouldRetry(context(EXCEPTION, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); assertThat(condition.shouldRetry(context(EXCEPTION_2, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(7); condition.requestSucceeded(context(EXCEPTION_2, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(EXCEPTION_2, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(11); } @Test public void nonFirstAttemptsAreNotFree() { TokenBucketRetryCondition condition = create(2, e -> 1); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(1); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(0); assertThat(condition.shouldRetry(context(EXCEPTION))).isFalse(); assertThat(condition.tokensAvailable()).isEqualTo(0); } @Test public void exceptionCostIsHonored() { // EXCEPTION costs 1, anything else costs 10 TokenBucketRetryCondition condition = create(20, e -> e == EXCEPTION ? 1 : 10); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(19); assertThat(condition.shouldRetry(context(EXCEPTION_2))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(9); assertThat(condition.shouldRetry(context(EXCEPTION_2))).isFalse(); assertThat(condition.tokensAvailable()).isEqualTo(9); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(8); } @Test public void successReleasesAcquiredCost() { ExecutionAttributes attributes = new ExecutionAttributes(); TokenBucketRetryCondition condition = create(20, e -> 10); assertThat(condition.shouldRetry(context(EXCEPTION, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(EXCEPTION, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(20); } @Test public void firstRequestSuccessReleasesOne() { TokenBucketRetryCondition condition = create(20, e -> 10); assertThat(condition.shouldRetry(context(null))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(11); condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(12); } @Test public void conditionSeemsToBeThreadSafe() throws InterruptedException { int bucketSize = 5; TokenBucketRetryCondition condition = create(bucketSize, e -> 1); AtomicInteger concurrentCalls = new AtomicInteger(0); AtomicBoolean failure = new AtomicBoolean(false); int parallelism = bucketSize * 2; ExecutorService executor = Executors.newFixedThreadPool(parallelism); for (int i = 0; i < parallelism; ++i) { executor.submit(() -> { try { for (int j = 0; j < 1000; ++j) { ExecutionAttributes attributes = new ExecutionAttributes(); if (condition.shouldRetry(context(EXCEPTION, attributes))) { int calls = concurrentCalls.addAndGet(1); if (calls > bucketSize) { failure.set(true); } Thread.sleep(1); concurrentCalls.addAndGet(-1); condition.requestSucceeded(context(EXCEPTION, attributes)); } else { Thread.sleep(1); } } } catch (Throwable t) { t.printStackTrace(); failure.set(true); } }); // Stagger the threads a bit. Thread.sleep(1); } executor.shutdown(); if (!executor.awaitTermination(1, TimeUnit.MINUTES)) { fail(); } assertThat(failure.get()).isFalse(); } private RetryPolicyContext context(SdkException lastException) { return RetryPolicyContext.builder() .executionAttributes(new ExecutionAttributes()) .exception(lastException) .build(); } private RetryPolicyContext context(SdkException lastException, ExecutionAttributes attributes) { return RetryPolicyContext.builder() .executionAttributes(attributes) .exception(lastException) .build(); } private TokenBucketRetryCondition create(int size, TokenBucketExceptionCostFunction function) { return TokenBucketRetryCondition.builder() .tokenBucketSize(size) .exceptionCostFunction(function) .build(); } }
1,622
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/DefaultSdkAutoConstructMapTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import org.junit.jupiter.api.Test; public class DefaultSdkAutoConstructMapTest { private static final DefaultSdkAutoConstructMap<String, String> AUTO_CONSTRUCT_MAP = DefaultSdkAutoConstructMap.getInstance(); @Test public void equal_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.equals(new HashMap<>())).isTrue(); } @Test public void hashCode_sameAsEmptyMap() { assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(new HashMap<>().hashCode()); // The hashCode is defined by the Map interface to be the hashCodes of // all the entries in the Map, so this should be 0. assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(0); } @Test public void toString_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.toString()).isEqualTo("{}"); } }
1,623
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/IdempotentUtilsTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; public class IdempotentUtilsTest { @Test public void resolveString_returns_givenString_when_nonnullString_is_passed() { String idempotencyToken = "120c7d4a-e982-4323-a53e-28989a0a9f26"; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_emptyString_when_emptyString_is_passed() { String idempotencyToken = ""; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_newUniqueToken_when_nullString_is_passed() { assertNotNull(IdempotentUtils.resolveString(null)); } }
1,624
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/Crc32ChecksumInputStreamTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.zip.CRC32; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.util.Crc32ChecksumCalculatingInputStream; /** * Test CRC32ChecksumInputStream can calculate CRC32 checksum correctly. */ public class Crc32ChecksumInputStreamTest { private static final String TEST_DATA = "Jason, Yifei, Zach"; @Test public void testCrc32Checksum() throws IOException { CRC32 crc32 = new CRC32(); crc32.update(TEST_DATA.getBytes()); long expectedCRC32Checksum = crc32.getValue(); Crc32ChecksumCalculatingInputStream crc32InputStream = new Crc32ChecksumCalculatingInputStream(new ByteArrayInputStream(TEST_DATA.getBytes())); while (crc32InputStream.read() != -1) { ; } assertEquals(expectedCRC32Checksum, crc32InputStream.getCrc32Checksum()); } }
1,625
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/VersionInfoTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; public final class VersionInfoTest { @Test public void versionIsTheSameAsMavenProject() throws Exception { assertThat(VersionInfo.SDK_VERSION).isEqualTo(getSdkVersionFromPom()); } private String getSdkVersionFromPom() throws URISyntaxException, IOException { Path pomPath = Paths.get(VersionInfo.class.getResource(".").toURI()).resolve("../../../../../../../pom.xml"); String pom = new String(Files.readAllBytes(pomPath)); Matcher match = Pattern.compile("<version>(.*)</version>").matcher(pom); if (match.find()) { return match.group(1); } throw new RuntimeException("Version not found in " + pomPath); } }
1,626
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/FileUtils.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.core.util; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import org.apache.commons.io.IOUtils; /** * Helper class that helps in creating and writing data to temporary files. * */ public class FileUtils { static final int ASCII_LOW = 33; // '!', skipping space for readability static final int ASCII_HIGH = 126; // include a line break character static final int modulo = ASCII_HIGH - ASCII_LOW + 2; private static final Random rand = new Random(); /** * Appends the given data to the file specified in the input and returns the * reference to the file. * * @param dataToAppend * @return reference to the file. */ public static File appendDataToTempFile(File file, String dataToAppend) throws IOException { FileWriter outputWriter = new FileWriter(file); try { outputWriter.append(dataToAppend); } finally { outputWriter.close(); } return file; } /** * Generate a random ASCII file of the specified number of bytes. The ASCII * characters ranges over all printable ASCII from 33 to 126 inclusive and * LF '\n', intentionally skipping space for readability. */ public static File generateRandomAsciiFile(long byteSize) throws IOException { return generateRandomAsciiFile(byteSize, true); } public static File generateRandomAsciiFile(long byteSize, boolean deleteOnExit) throws IOException { File file = File.createTempFile("CryptoTestUtils", ".txt"); System.out.println("Generating random ASCII file with size: " + byteSize + " at " + file); if (deleteOnExit) { file.deleteOnExit(); } OutputStream out = new FileOutputStream(file); int BUFSIZE = 1024 * 8; byte[] buf = new byte[1024 * 8]; long counts = byteSize / BUFSIZE; try { while (counts-- > 0) { IOUtils.write(fillRandomAscii(buf), out); } int remainder = (int) byteSize % BUFSIZE; if (remainder > 0) { buf = new byte[remainder]; IOUtils.write(fillRandomAscii(buf), out); } } finally { out.close(); } return file; } private static byte[] fillRandomAscii(byte[] bytes) { rand.nextBytes(bytes); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; if (b < ASCII_LOW || b > ASCII_HIGH) { byte c = (byte) (b % modulo); if (c < 0) { c = (byte) (c + modulo); } bytes[i] = (byte) (c + ASCII_LOW); if (bytes[i] > ASCII_HIGH) { bytes[i] = (byte) '\n'; } } } return bytes; } }
1,627
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/PaginatorUtilsTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.junit.jupiter.api.Test; public class PaginatorUtilsTest { @Test public void nullOutputToken_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(null)); } @Test public void nonNullString_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable("next")); } @Test public void nonNullInteger_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable(12)); } @Test public void emptyCollection_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(new ArrayList<>())); } @Test public void nonEmptyCollection_shouldReturnTrue() { assertTrue(PaginatorUtils.isOutputTokenAvailable(Arrays.asList("foo", "bar"))); } @Test public void emptyMap_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(new HashMap<>())); } @Test public void nonEmptyMap_shouldReturnTrue() { HashMap<String, String> outputTokens = new HashMap<>(); outputTokens.put("foo", "bar"); assertTrue(PaginatorUtils.isOutputTokenAvailable(outputTokens)); } @Test public void sdkAutoConstructList_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(DefaultSdkAutoConstructList.getInstance())); } @Test public void sdkAutoConstructMap_shouldReturnFalse() { assertFalse(PaginatorUtils.isOutputTokenAvailable(DefaultSdkAutoConstructMap.getInstance())); } }
1,628
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/RetryUtilsTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.RetryUtils; import software.amazon.awssdk.http.HttpStatusCode; public class RetryUtilsTest { @Test public void nonSdkServiceException_shouldReturnFalse() { SdkClientException exception = SdkClientException.builder().message("exception").build(); assertThat(RetryUtils.isServiceException(exception)).isFalse(); assertThat(RetryUtils.isClockSkewException(exception)).isFalse(); assertThat(RetryUtils.isThrottlingException(exception)).isFalse(); assertThat(RetryUtils.isRequestEntityTooLargeException(exception)).isFalse(); } @Test public void statusCode429_isThrottlingExceptionShouldReturnTrue() { SdkServiceException throttlingException = SdkServiceException.builder().message("Throttling").statusCode(429).build(); assertThat(RetryUtils.isThrottlingException(throttlingException)).isTrue(); } @Test public void sdkServiceException_shouldReturnFalseIfNotOverridden() { SdkServiceException clockSkewException = SdkServiceException.builder().message("default").build(); assertThat(RetryUtils.isClockSkewException(clockSkewException)).isFalse(); } @Test public void statusCode413_isRequestEntityTooLargeShouldReturnTrue() { SdkServiceException exception = SdkServiceException.builder() .message("boom") .statusCode(HttpStatusCode.REQUEST_TOO_LONG) .build(); assertThat(RetryUtils.isRequestEntityTooLargeException(exception)).isTrue(); } }
1,629
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/DefaultSdkAutoConstructListTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.LinkedList; import org.junit.jupiter.api.Test; public class DefaultSdkAutoConstructListTest { private static final DefaultSdkAutoConstructList<String> INSTANCE = DefaultSdkAutoConstructList.getInstance(); @Test public void equals_emptyList() { assertThat(INSTANCE.equals(new LinkedList<>())).isTrue(); } @Test public void hashCode_sameAsEmptyList() { assertThat(INSTANCE.hashCode()).isEqualTo(new LinkedList<>().hashCode()); // The formula for calculating the hashCode is specified by the List // interface. For an empty list, it should be 1. assertThat(INSTANCE.hashCode()).isEqualTo(1); } @Test public void toString_emptyList() { assertThat(INSTANCE.toString()).isEqualTo("[]"); } }
1,630
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/ThrowableUtilsTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.util.ThrowableUtils; public class ThrowableUtilsTest { @Test public void typical() { Throwable a = new Throwable(); Throwable b = new Throwable(a); assertSame(a, ThrowableUtils.getRootCause(b)); assertSame(a, ThrowableUtils.getRootCause(a)); } @Test public void circularRef() { // God forbidden Throwable a = new Throwable(); Throwable b = new Throwable(a); a.initCause(b); assertSame(b, ThrowableUtils.getRootCause(b)); assertSame(a, ThrowableUtils.getRootCause(a)); } @Test public void nullCause() { Throwable a = new Throwable(); assertSame(a, ThrowableUtils.getRootCause(a)); } @Test public void simplyNull() { assertNull(ThrowableUtils.getRootCause(null)); } }
1,631
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/SdkUserAgentTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.JavaSystemSetting; public class SdkUserAgentTest { @Test public void userAgent() { String userAgent = SdkUserAgent.create().userAgent(); assertNotNull(userAgent); Arrays.stream(userAgent.split(" ")).forEach(str -> assertThat(isValidInput(str)).isTrue()); } @Test public void userAgent_HasVendor() { System.setProperty(JavaSystemSetting.JAVA_VENDOR.property(), "finks"); String userAgent = SdkUserAgent.create().getUserAgent(); System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); assertThat(userAgent).contains("vendor/finks"); } @Test public void userAgent_HasUnknownVendor() { System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); String userAgent = SdkUserAgent.create().getUserAgent(); assertThat(userAgent).contains("vendor/unknown"); } private boolean isValidInput(String input) { return input.startsWith("(") || input.contains("/") && input.split("/").length == 2; } }
1,632
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/AsyncRequestBodyTest.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.core.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import io.reactivex.Flowable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.utils.BinaryUtils; public class AsyncRequestBodyTest { private static final String testString = "Hello!"; private static final Path path; static { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); path = fs.getPath("./test"); try { Files.write(path, testString.getBytes()); } catch (IOException e) { e.printStackTrace(); } } @ParameterizedTest @MethodSource("contentIntegrityChecks") void hasCorrectLength(AsyncRequestBody asyncRequestBody) { assertEquals(testString.length(), asyncRequestBody.contentLength().get()); } @ParameterizedTest @MethodSource("contentIntegrityChecks") void hasCorrectContent(AsyncRequestBody asyncRequestBody) throws InterruptedException { StringBuilder sb = new StringBuilder(); CountDownLatch done = new CountDownLatch(1); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(buffer -> { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); sb.append(new String(bytes, StandardCharsets.UTF_8)); }) { @Override public void onError(Throwable t) { super.onError(t); done.countDown(); } @Override public void onComplete() { super.onComplete(); done.countDown(); } }; asyncRequestBody.subscribe(subscriber); done.await(); assertEquals(testString, sb.toString()); } private static AsyncRequestBody[] contentIntegrityChecks() { return new AsyncRequestBody[] { AsyncRequestBody.fromString(testString), AsyncRequestBody.fromFile(path) }; } @Test void fromBytesCopiesTheProvidedByteArray() { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); byte[] bytesClone = bytes.clone(); AsyncRequestBody asyncRequestBody = AsyncRequestBody.fromBytes(bytes); for (int i = 0; i < bytes.length; i++) { bytes[i] += 1; } AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); byte[] publishedByteArray = BinaryUtils.copyAllBytesFrom(publishedBuffer.get()); assertArrayEquals(bytesClone, publishedByteArray); } @Test void fromBytesUnsafeDoesNotCopyTheProvidedByteArray() { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); AsyncRequestBody asyncRequestBody = AsyncRequestBody.fromBytesUnsafe(bytes); for (int i = 0; i < bytes.length; i++) { bytes[i] += 1; } AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); byte[] publishedByteArray = BinaryUtils.copyAllBytesFrom(publishedBuffer.get()); assertArrayEquals(bytes, publishedByteArray); } @ParameterizedTest @MethodSource("safeByteBufferBodyBuilders") void safeByteBufferBuildersCopyTheProvidedBuffer(Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); byte[] bytesClone = bytes.clone(); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(ByteBuffer.wrap(bytes)); for (int i = 0; i < bytes.length; i++) { bytes[i] += 1; } AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); byte[] publishedByteArray = BinaryUtils.copyAllBytesFrom(publishedBuffer.get()); assertArrayEquals(bytesClone, publishedByteArray); } private static Function<ByteBuffer, AsyncRequestBody>[] safeByteBufferBodyBuilders() { Function<ByteBuffer, AsyncRequestBody> fromByteBuffer = AsyncRequestBody::fromByteBuffer; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffer = AsyncRequestBody::fromRemainingByteBuffer; Function<ByteBuffer, AsyncRequestBody> fromByteBuffers = AsyncRequestBody::fromByteBuffers; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffers = AsyncRequestBody::fromRemainingByteBuffers; return new Function[] {fromByteBuffer, fromRemainingByteBuffer, fromByteBuffers, fromRemainingByteBuffers}; } @ParameterizedTest @MethodSource("unsafeByteBufferBodyBuilders") void unsafeByteBufferBuildersDoNotCopyTheProvidedBuffer(Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(ByteBuffer.wrap(bytes)); for (int i = 0; i < bytes.length; i++) { bytes[i] += 1; } AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); byte[] publishedByteArray = BinaryUtils.copyAllBytesFrom(publishedBuffer.get()); assertArrayEquals(bytes, publishedByteArray); } private static Function<ByteBuffer, AsyncRequestBody>[] unsafeByteBufferBodyBuilders() { Function<ByteBuffer, AsyncRequestBody> fromByteBuffer = AsyncRequestBody::fromByteBufferUnsafe; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffer = AsyncRequestBody::fromRemainingByteBufferUnsafe; Function<ByteBuffer, AsyncRequestBody> fromByteBuffers = AsyncRequestBody::fromByteBuffersUnsafe; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffers = AsyncRequestBody::fromRemainingByteBuffersUnsafe; return new Function[] {fromByteBuffer, fromRemainingByteBuffer, fromByteBuffers, fromRemainingByteBuffers}; } @ParameterizedTest @MethodSource("nonRewindingByteBufferBodyBuilders") void nonRewindingByteBufferBuildersReadFromTheInputBufferPosition( Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(bytes); int expectedPosition = bytes.length / 2; bb.position(expectedPosition); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(bb); AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); int remaining = bb.remaining(); assertEquals(remaining, publishedBuffer.get().remaining()); for (int i = 0; i < remaining; i++) { assertEquals(bb.get(), publishedBuffer.get().get()); } } private static Function<ByteBuffer, AsyncRequestBody>[] nonRewindingByteBufferBodyBuilders() { Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffer = AsyncRequestBody::fromRemainingByteBuffer; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBufferUnsafe = AsyncRequestBody::fromRemainingByteBufferUnsafe; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffers = AsyncRequestBody::fromRemainingByteBuffers; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffersUnsafe = AsyncRequestBody::fromRemainingByteBuffersUnsafe; return new Function[] {fromRemainingByteBuffer, fromRemainingByteBufferUnsafe, fromRemainingByteBuffers, fromRemainingByteBuffersUnsafe}; } @ParameterizedTest @MethodSource("safeNonRewindingByteBufferBodyBuilders") void safeNonRewindingByteBufferBuildersCopyFromTheInputBufferPosition( Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(bytes); int expectedPosition = bytes.length / 2; bb.position(expectedPosition); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(bb); AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); int remaining = bb.remaining(); assertEquals(remaining, publishedBuffer.get().capacity()); for (int i = 0; i < remaining; i++) { assertEquals(bb.get(), publishedBuffer.get().get()); } } private static Function<ByteBuffer, AsyncRequestBody>[] safeNonRewindingByteBufferBodyBuilders() { Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffer = AsyncRequestBody::fromRemainingByteBuffer; Function<ByteBuffer, AsyncRequestBody> fromRemainingByteBuffers = AsyncRequestBody::fromRemainingByteBuffers; return new Function[] {fromRemainingByteBuffer, fromRemainingByteBuffers}; } @ParameterizedTest @MethodSource("rewindingByteBufferBodyBuilders") void rewindingByteBufferBuildersDoNotRewindTheInputBuffer(Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(bytes); int expectedPosition = bytes.length / 2; bb.position(expectedPosition); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(bb); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(buffer -> { }); asyncRequestBody.subscribe(subscriber); assertEquals(expectedPosition, bb.position()); } @ParameterizedTest @MethodSource("rewindingByteBufferBodyBuilders") void rewindingByteBufferBuildersReadTheInputBufferFromTheBeginning( Function<ByteBuffer, AsyncRequestBody> bodyBuilder) { byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(bytes); bb.position(bytes.length / 2); AsyncRequestBody asyncRequestBody = bodyBuilder.apply(bb); AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set); asyncRequestBody.subscribe(subscriber); assertEquals(0, publishedBuffer.get().position()); publishedBuffer.get().rewind(); bb.rewind(); assertEquals(bb, publishedBuffer.get()); } private static Function<ByteBuffer, AsyncRequestBody>[] rewindingByteBufferBodyBuilders() { Function<ByteBuffer, AsyncRequestBody> fromByteBuffer = AsyncRequestBody::fromByteBuffer; Function<ByteBuffer, AsyncRequestBody> fromByteBufferUnsafe = AsyncRequestBody::fromByteBufferUnsafe; Function<ByteBuffer, AsyncRequestBody> fromByteBuffers = AsyncRequestBody::fromByteBuffers; Function<ByteBuffer, AsyncRequestBody> fromByteBuffersUnsafe = AsyncRequestBody::fromByteBuffersUnsafe; return new Function[] {fromByteBuffer, fromByteBufferUnsafe, fromByteBuffers, fromByteBuffersUnsafe}; } @ParameterizedTest @ValueSource(strings = {"US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16"}) void charsetsAreConvertedToTheCorrectContentType(Charset charset) { AsyncRequestBody requestBody = AsyncRequestBody.fromString("hello world", charset); assertEquals("text/plain; charset=" + charset.name(), requestBody.contentType()); } @Test void stringConstructorHasCorrectDefaultContentType() { AsyncRequestBody requestBody = AsyncRequestBody.fromString("hello world"); assertEquals("text/plain; charset=UTF-8", requestBody.contentType()); } @Test void fileConstructorHasCorrectContentType() { AsyncRequestBody requestBody = AsyncRequestBody.fromFile(path); assertEquals(Mimetype.MIMETYPE_OCTET_STREAM, requestBody.contentType()); } @Test void bytesArrayConstructorHasCorrectContentType() { AsyncRequestBody requestBody = AsyncRequestBody.fromBytes("hello world".getBytes()); assertEquals(Mimetype.MIMETYPE_OCTET_STREAM, requestBody.contentType()); } @Test void bytesBufferConstructorHasCorrectContentType() { ByteBuffer byteBuffer = ByteBuffer.wrap("hello world".getBytes()); AsyncRequestBody requestBody = AsyncRequestBody.fromByteBuffer(byteBuffer); assertEquals(Mimetype.MIMETYPE_OCTET_STREAM, requestBody.contentType()); } @Test void emptyBytesConstructorHasCorrectContentType() { AsyncRequestBody requestBody = AsyncRequestBody.empty(); assertEquals(Mimetype.MIMETYPE_OCTET_STREAM, requestBody.contentType()); } @Test void publisherConstructorHasCorrectContentType() { List<String> requestBodyStrings = Lists.newArrayList("A", "B", "C"); List<ByteBuffer> bodyBytes = requestBodyStrings.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Publisher<ByteBuffer> bodyPublisher = Flowable.fromIterable(bodyBytes); AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(bodyPublisher); assertEquals(Mimetype.MIMETYPE_OCTET_STREAM, requestBody.contentType()); } }
1,633
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/BlockingInputStreamAsyncRequestBodyTest.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.core.async; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber; import software.amazon.awssdk.utils.async.StoringSubscriber; class BlockingInputStreamAsyncRequestBodyTest { @Test public void doBlockingWrite_waitsForSubscription() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); try { BlockingInputStreamAsyncRequestBody requestBody = AsyncRequestBody.forBlockingInputStream(0L); executor.schedule(() -> requestBody.subscribe(new StoringSubscriber<>(1)), 10, MILLISECONDS); requestBody.writeInputStream(new StringInputStream("")); } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void doBlockingWrite_failsIfSubscriptionNeverComes() { BlockingInputStreamAsyncRequestBody requestBody = new BlockingInputStreamAsyncRequestBody(0L, Duration.ofSeconds(1)); assertThatThrownBy(() -> requestBody.writeInputStream(new StringInputStream(""))) .hasMessageContaining("The service request was not made"); } @Test public void doBlockingWrite_writesToSubscriber() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); try { BlockingInputStreamAsyncRequestBody requestBody = AsyncRequestBody.forBlockingInputStream(2L); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(4); requestBody.subscribe(subscriber); requestBody.writeInputStream(new ByteArrayInputStream(new byte[] { 0, 1 })); ByteBuffer out = ByteBuffer.allocate(4); assertThat(subscriber.transferTo(out)).isEqualTo(END_OF_STREAM); out.flip(); assertThat(out.remaining()).isEqualTo(2); assertThat(out.get()).isEqualTo((byte) 0); assertThat(out.get()).isEqualTo((byte) 1); } finally { executor.shutdownNow(); } } }
1,634
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/ChunkBufferTest.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.core.async; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.core.internal.async.ChunkBuffer; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.StringUtils; class ChunkBufferTest { @ParameterizedTest @ValueSource(ints = {1, 6, 10, 23, 25}) void numberOfChunk_Not_MultipleOfTotalBytes_KnownLength(int totalBytes) { int bufferSize = 5; String inputString = RandomStringUtils.randomAscii(totalBytes); ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(bufferSize) .totalBytes(inputString.getBytes(StandardCharsets.UTF_8).length) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(ByteBuffer.wrap(inputString.getBytes(StandardCharsets.UTF_8))); AtomicInteger index = new AtomicInteger(0); int count = (int) Math.ceil(totalBytes / (double) bufferSize); int remainder = totalBytes % bufferSize; byteBuffers.forEach(r -> { int i = index.get(); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8))) { byte[] expected; if (i == count - 1 && remainder != 0) { expected = new byte[remainder]; } else { expected = new byte[bufferSize]; } inputStream.skip(i * bufferSize); inputStream.read(expected); byte[] actualBytes = BinaryUtils.copyBytesFrom(r); assertThat(actualBytes).isEqualTo(expected); index.incrementAndGet(); } catch (IOException e) { throw new RuntimeException(e); } }); } @ParameterizedTest @ValueSource(ints = {1, 6, 10, 23, 25}) void numberOfChunk_Not_MultipleOfTotalBytes_UnknownLength(int totalBytes) { int bufferSize = 5; String inputString = RandomStringUtils.randomAscii(totalBytes); ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(bufferSize) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(ByteBuffer.wrap(inputString.getBytes(StandardCharsets.UTF_8))); AtomicInteger index = new AtomicInteger(0); int count = (int) Math.ceil(totalBytes / (double) bufferSize); int remainder = totalBytes % bufferSize; byteBuffers.forEach(r -> { int i = index.get(); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8))) { byte[] expected; if (i == count - 1 && remainder != 0) { expected = new byte[remainder]; } else { expected = new byte[bufferSize]; } inputStream.skip(i * bufferSize); inputStream.read(expected); byte[] actualBytes = BinaryUtils.copyBytesFrom(r); assertThat(actualBytes).isEqualTo(expected); index.incrementAndGet(); } catch (IOException e) { throw new RuntimeException(e); } }); } @Test void zeroTotalBytesAsInput_returnsZeroByte_KnownLength() { byte[] zeroByte = new byte[0]; ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(5) .totalBytes(zeroByte.length) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(ByteBuffer.wrap(zeroByte)); AtomicInteger iteratedCounts = new AtomicInteger(); byteBuffers.forEach(r -> { iteratedCounts.getAndIncrement(); }); assertThat(iteratedCounts.get()).isEqualTo(1); } @Test void zeroTotalBytesAsInput_returnsZeroByte_UnknownLength() { byte[] zeroByte = new byte[0]; ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(5) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(ByteBuffer.wrap(zeroByte)); AtomicInteger iteratedCounts = new AtomicInteger(); byteBuffers.forEach(r -> { iteratedCounts.getAndIncrement(); }); assertThat(iteratedCounts.get()).isEqualTo(1); } @Test void emptyAllocatedBytes_returnSameNumberOfEmptyBytes_knownLength() { int totalBytes = 17; int bufferSize = 5; ByteBuffer wrap = ByteBuffer.allocate(totalBytes); ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(bufferSize) .totalBytes(wrap.remaining()) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(wrap); AtomicInteger iteratedCounts = new AtomicInteger(); byteBuffers.forEach(r -> { iteratedCounts.getAndIncrement(); if (iteratedCounts.get() * bufferSize < totalBytes) { // array of empty bytes assertThat(BinaryUtils.copyBytesFrom(r)).isEqualTo(ByteBuffer.allocate(bufferSize).array()); } else { assertThat(BinaryUtils.copyBytesFrom(r)).isEqualTo(ByteBuffer.allocate(totalBytes % bufferSize).array()); } }); assertThat(iteratedCounts.get()).isEqualTo(4); } @Test void emptyAllocatedBytes_returnSameNumberOfEmptyBytes_unknownLength() { int totalBytes = 17; int bufferSize = 5; ByteBuffer wrap = ByteBuffer.allocate(totalBytes); ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(bufferSize) .build(); Iterable<ByteBuffer> byteBuffers = chunkBuffer.split(wrap); AtomicInteger iteratedCounts = new AtomicInteger(); byteBuffers.forEach(r -> { iteratedCounts.getAndIncrement(); if (iteratedCounts.get() * bufferSize < totalBytes) { // array of empty bytes assertThat(BinaryUtils.copyBytesFrom(r)).isEqualTo(ByteBuffer.allocate(bufferSize).array()); } else { assertThat(BinaryUtils.copyBytesFrom(r)).isEqualTo(ByteBuffer.allocate(totalBytes % bufferSize).array()); } }); assertThat(iteratedCounts.get()).isEqualTo(3); Optional<ByteBuffer> lastBuffer = chunkBuffer.getBufferedData(); assertThat(lastBuffer).isPresent(); assertThat(lastBuffer.get().remaining()).isEqualTo(2); } /** * * Total bytes 11(ChunkSize) 3 (threads) * * Buffering Size of 5 * threadOne 22222222222 * threadTwo 33333333333 * threadThree 11111111111 * * * Streaming sequence as below * * * start 22222222222 * 22222 * 22222 * end 22222222222 * * * start streaming 33333333333 * 2 is from previous sequence which is buffered * 23333 * 33333 * end 33333333333 * * * start 11111111111 * 33 is from previous sequence which is buffered * * 33111 * 11111 * 111 * end 11111111111 * 111 is given as output since we consumed all the total bytes* */ @Test void concurrentTreads_calling_bufferAndCreateChunks_knownLength() throws ExecutionException, InterruptedException { int totalBytes = 17; int bufferSize = 5; int threads = 8; ByteBuffer wrap = ByteBuffer.allocate(totalBytes); ChunkBuffer chunkBuffer = ChunkBuffer.builder() .bufferSize(bufferSize) .totalBytes(wrap.remaining() * threads) .build(); ExecutorService service = Executors.newFixedThreadPool(threads); Collection<Future<Iterable>> futures; AtomicInteger counter = new AtomicInteger(0); futures = IntStream.range(0, threads).<Future<Iterable>>mapToObj(t -> service.submit(() -> { String inputString = StringUtils.repeat(Integer.toString(counter.incrementAndGet()), totalBytes); return chunkBuffer.split(ByteBuffer.wrap(inputString.getBytes(StandardCharsets.UTF_8))); })).collect(Collectors.toCollection(() -> new ArrayList<>(threads))); AtomicInteger filledBuffers = new AtomicInteger(0); AtomicInteger remainderBytesBuffers = new AtomicInteger(0); AtomicInteger otherSizeBuffers = new AtomicInteger(0); AtomicInteger remainderBytes = new AtomicInteger(0); for (Future<Iterable> bufferedFuture : futures) { Iterable<ByteBuffer> buffers = bufferedFuture.get(); buffers.forEach(b -> { if (b.remaining() == bufferSize) { filledBuffers.incrementAndGet(); } else if (b.remaining() == ((totalBytes * threads) % bufferSize)) { remainderBytesBuffers.incrementAndGet(); remainderBytes.set(b.remaining()); } else { otherSizeBuffers.incrementAndGet(); } }); } assertThat(filledBuffers.get()).isEqualTo((totalBytes * threads) / bufferSize); assertThat(remainderBytes.get()).isEqualTo((totalBytes * threads) % bufferSize); assertThat(remainderBytesBuffers.get()).isOne(); assertThat(otherSizeBuffers.get()).isZero(); } }
1,635
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/ResponsePublisherTest.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.core.async; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class ResponsePublisherTest { @Test void equalsAndHashcode() { EqualsVerifier.forClass(ResponsePublisher.class) .withNonnullFields("response", "publisher") .verify(); } }
1,636
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/CompressionAsyncRequestBodyTckTest.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.core.async; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import io.reactivex.Flowable; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.internal.async.CompressionAsyncRequestBody; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; public class CompressionAsyncRequestBodyTckTest extends PublisherVerification<ByteBuffer> { private static final FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); private static final Path rootDir = fs.getRootDirectories().iterator().next(); private static final int MAX_ELEMENTS = 1000; private static final int CHUNK_SIZE = 128 * 1024; private static final Compressor compressor = new GzipCompressor(); public CompressionAsyncRequestBodyTckTest() { super(new TestEnvironment()); } @Override public long maxElementsFromPublisher() { return MAX_ELEMENTS; } @Override public Publisher<ByteBuffer> createPublisher(long n) { return CompressionAsyncRequestBody.builder() .asyncRequestBody(customAsyncRequestBodyFromFileWithoutContentLength(n)) .compressor(compressor) .build(); } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } private static AsyncRequestBody customAsyncRequestBodyFromFileWithoutContentLength(long nChunks) { return new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Flowable.fromPublisher(AsyncRequestBody.fromFile(fileOfNChunks(nChunks))).subscribe(s); } }; } private static Path fileOfNChunks(long nChunks) { String name = String.format("%d-chunks-file.dat", nChunks); Path p = rootDir.resolve(name); if (!Files.exists(p)) { try (OutputStream os = Files.newOutputStream(p)) { os.write(createCompressibleArrayOfNChunks(nChunks)); } catch (IOException e) { throw new UncheckedIOException(e); } } return p; } private static byte[] createCompressibleArrayOfNChunks(long nChunks) { int size = Math.toIntExact(nChunks * CHUNK_SIZE); ByteBuffer data = ByteBuffer.allocate(size); byte[] a = new byte[size / 4]; byte[] b = new byte[size / 4]; Arrays.fill(a, (byte) 'a'); Arrays.fill(b, (byte) 'b'); data.put(a); data.put(b); data.put(a); data.put(b); return data.array(); } }
1,637
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/ChecksumCalculatingAsyncRequestBodyTckTest.java
package software.amazon.awssdk.core.async; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.internal.async.ChecksumCalculatingAsyncRequestBody; public class ChecksumCalculatingAsyncRequestBodyTckTest extends PublisherVerification<ByteBuffer> { private static final int MAX_ELEMENTS = 1000; private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); private final Path rootDir = fs.getRootDirectories().iterator().next(); private static final int CHUNK_SIZE = 16 * 1024; private final byte[] chunkData = new byte[CHUNK_SIZE]; public ChecksumCalculatingAsyncRequestBodyTckTest() throws IOException { super(new TestEnvironment()); } @Override public long maxElementsFromPublisher() { return MAX_ELEMENTS; } @Override public Publisher<ByteBuffer> createPublisher(long n) { return ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromFile(fileOfNChunks(n))) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); } private Path fileOfNChunks(long nChunks) { String name = String.format("%d-chunks-file.dat", nChunks); Path p = rootDir.resolve(name); if (!Files.exists(p)) { try (OutputStream os = Files.newOutputStream(p)) { for (int i = 0; i < nChunks; ++i) { os.write(chunkData); } } catch (IOException e) { throw new UncheckedIOException(e); } } return p; } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } }
1,638
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/FileAsyncRequestPublisherTckTest.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.core.async; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import org.reactivestreams.Publisher; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody; import software.amazon.awssdk.utils.FunctionalUtils; /** * TCK verification test for {@link FileAsyncRequestBody}. */ public class FileAsyncRequestPublisherTckTest extends org.reactivestreams.tck.PublisherVerification<ByteBuffer> { // same as `FileAsyncRequestProvider.DEFAULT_CHUNK_SIZE`: private static final int CHUNK_SIZE = 16 * 1024; private static final int MAX_ELEMENTS = 1000; private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); private final Path rootDir = fs.getRootDirectories().iterator().next(); private final byte[] chunkData = new byte[CHUNK_SIZE]; public FileAsyncRequestPublisherTckTest() throws IOException { super(new TestEnvironment()); } // prevent some tests from trying to create publishers with more elements // than this since it would be impractical. For example, one test attempts // to create a publisher with Long.MAX_VALUE elements @Override public long maxElementsFromPublisher() { return MAX_ELEMENTS; } @Override public Publisher<ByteBuffer> createPublisher(long elements) { return FileAsyncRequestBody.builder() .chunkSizeInBytes(CHUNK_SIZE) .path(fileOfNChunks(elements)) .build(); } @Override public Publisher<ByteBuffer> createFailedPublisher() { // tests properly failing on non existing files: Path path = rootDir.resolve("createFailedPublisher" + UUID.randomUUID()); FunctionalUtils.invokeSafely(() -> Files.write(path, "test".getBytes(StandardCharsets.UTF_8))); FileAsyncRequestBody fileAsyncRequestBody = FileAsyncRequestBody.builder() .chunkSizeInBytes(CHUNK_SIZE) .path(path) .build(); FunctionalUtils.invokeSafely(() -> Files.delete(path)); return fileAsyncRequestBody; } private Path fileOfNChunks(long nChunks) { String name = String.format("%d-chunks-file.dat", nChunks); Path p = rootDir.resolve(name); if (!Files.exists(p)) { try (OutputStream os = Files.newOutputStream(p)) { for (int i = 0; i < nChunks; ++i) { os.write(chunkData); } } catch (IOException e) { throw new UncheckedIOException(e); } } return p; } }
1,639
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/BlockingOutputStreamAsyncRequestBodyTest.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.core.async; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.utils.CancellableOutputStream; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber; import software.amazon.awssdk.utils.async.StoringSubscriber; class BlockingOutputStreamAsyncRequestBodyTest { @Test public void outputStream_waitsForSubscription() throws IOException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); try { BlockingOutputStreamAsyncRequestBody requestBody = AsyncRequestBody.forBlockingOutputStream(0L); executor.schedule(() -> requestBody.subscribe(new StoringSubscriber<>(1)), 100, MILLISECONDS); try (OutputStream stream = requestBody.outputStream()) { stream.write('h'); } } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void outputStream_failsIfSubscriptionNeverComes() { BlockingOutputStreamAsyncRequestBody requestBody = new BlockingOutputStreamAsyncRequestBody(0L, Duration.ofSeconds(1)); assertThatThrownBy(requestBody::outputStream).hasMessageContaining("The service request was not made"); } @Test public void outputStream_writesToSubscriber() throws IOException { BlockingOutputStreamAsyncRequestBody requestBody = AsyncRequestBody.forBlockingOutputStream(0L); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(4); requestBody.subscribe(subscriber); CancellableOutputStream outputStream = requestBody.outputStream(); outputStream.write(0); outputStream.write(1); outputStream.close(); ByteBuffer out = ByteBuffer.allocate(4); assertThat(subscriber.transferTo(out)).isEqualTo(END_OF_STREAM); out.flip(); assertThat(out.remaining()).isEqualTo(2); assertThat(out.get()).isEqualTo((byte) 0); assertThat(out.get()).isEqualTo((byte) 1); } }
1,640
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/SimpleSubscriberTckTest.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.core.async; import java.nio.ByteBuffer; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.http.async.SimpleSubscriber; /** * TCK verifiation test for {@link SimpleSubscriber}. */ public class SimpleSubscriberTckTest extends org.reactivestreams.tck.SubscriberBlackboxVerification<ByteBuffer> { public SimpleSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber() { return new SimpleSubscriber(buffer -> { // ignore }); } @Override public ByteBuffer createElement(int i) { return ByteBuffer.wrap(String.valueOf(i).getBytes()); } }
1,641
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/AsyncRequestBodyConfigurationTest.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.core.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class AsyncRequestBodyConfigurationTest { @Test void equalsHashCode() { EqualsVerifier.forClass(AsyncRequestBodySplitConfiguration.class) .verify(); } @ParameterizedTest @ValueSource(longs = {0, -1}) void nonPositiveValue_shouldThrowException(long size) { assertThatThrownBy(() -> AsyncRequestBodySplitConfiguration.builder() .chunkSizeInBytes(size) .build()) .hasMessageContaining("must be positive"); assertThatThrownBy(() -> AsyncRequestBodySplitConfiguration.builder() .bufferSizeInBytes(size) .build()) .hasMessageContaining("must be positive"); } @Test void toBuilder_shouldCopyAllFields() { AsyncRequestBodySplitConfiguration config = AsyncRequestBodySplitConfiguration.builder() .bufferSizeInBytes(1L) .chunkSizeInBytes(2L) .build(); assertThat(config.toBuilder().build()).isEqualTo(config); } }
1,642
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/AsyncRequestBodyFromInputStreamConfigurationTest.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.core.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.io.InputStream; import java.util.concurrent.ExecutorService; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class AsyncRequestBodyFromInputStreamConfigurationTest { @Test void equalsHashcode() { EqualsVerifier.forClass(AsyncRequestBodyFromInputStreamConfiguration.class) .verify(); } @Test void toBuilder_shouldCopyProperties() { InputStream inputStream = mock(InputStream.class); ExecutorService executorService = mock(ExecutorService.class); AsyncRequestBodyFromInputStreamConfiguration configuration = AsyncRequestBodyFromInputStreamConfiguration.builder() .inputStream(inputStream) .contentLength(10L) .executor(executorService) .maxReadLimit(10) .build(); assertThat(configuration.toBuilder().build()).isEqualTo(configuration); } @Test void inputStreamIsNull_shouldThrowException() { assertThatThrownBy(() -> AsyncRequestBodyFromInputStreamConfiguration.builder() .executor(mock(ExecutorService.class)) .build()) .isInstanceOf(NullPointerException.class).hasMessageContaining("inputStream"); } @Test void executorIsNull_shouldThrowException() { assertThatThrownBy(() -> AsyncRequestBodyFromInputStreamConfiguration.builder() .inputStream(mock(InputStream.class)) .build()) .isInstanceOf(NullPointerException.class).hasMessageContaining("executor"); } @ParameterizedTest @ValueSource(ints = {0, -1}) void readLimitNotPositive_shouldThrowException(int value) { assertThatThrownBy(() -> AsyncRequestBodyFromInputStreamConfiguration.builder() .inputStream(mock(InputStream.class)) .executor(mock(ExecutorService.class)) .maxReadLimit(value) .build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("maxReadLimit"); } @Test void contentLengthNegative_shouldThrowException() { assertThatThrownBy(() -> AsyncRequestBodyFromInputStreamConfiguration.builder() .inputStream(mock(InputStream.class)) .executor(mock(ExecutorService.class)) .contentLength(-1L) .build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("contentLength"); } }
1,643
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/SdkPublishersTest.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.core.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.internal.async.SdkPublishers; import utils.FakePublisher; import utils.FakeSdkPublisher; public class SdkPublishersTest { @Test public void envelopeWrappedPublisher() { FakePublisher<ByteBuffer> fakePublisher = new FakePublisher<>(); Publisher<ByteBuffer> wrappedPublisher = SdkPublishers.envelopeWrappedPublisher(fakePublisher, "prefix:", ":suffix"); FakeByteBufferSubscriber fakeSubscriber = new FakeByteBufferSubscriber(); wrappedPublisher.subscribe(fakeSubscriber); fakePublisher.publish(ByteBuffer.wrap("content".getBytes(StandardCharsets.UTF_8))); fakePublisher.complete(); assertThat(fakeSubscriber.recordedEvents()).containsExactly("prefix:content", ":suffix"); } @Test public void mapTransformsCorrectly() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); FakeStringSubscriber fakeSubscriber = new FakeStringSubscriber(); fakePublisher.map(String::toUpperCase).subscribe(fakeSubscriber); fakePublisher.publish("one"); fakePublisher.publish("two"); fakePublisher.complete(); assertThat(fakeSubscriber.recordedEvents()).containsExactly("ONE", "TWO"); assertThat(fakeSubscriber.isComplete()).isTrue(); assertThat(fakeSubscriber.isError()).isFalse(); } @Test public void mapHandlesError() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); FakeStringSubscriber fakeSubscriber = new FakeStringSubscriber(); RuntimeException exception = new IllegalArgumentException("Twos are not supported"); fakePublisher.map(s -> { if ("two".equals(s)) { throw exception; } return s.toUpperCase(); }).subscribe(fakeSubscriber); fakePublisher.publish("one"); fakePublisher.publish("two"); fakePublisher.publish("three"); assertThat(fakeSubscriber.recordedEvents()).containsExactly("ONE"); assertThat(fakeSubscriber.isComplete()).isFalse(); assertThat(fakeSubscriber.isError()).isTrue(); assertThat(fakeSubscriber.recordedErrors()).containsExactly(exception); } @Test public void subscribeHandlesError() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); RuntimeException exception = new IllegalArgumentException("Failure!"); CompletableFuture<Void> subscribeFuture = fakePublisher.subscribe(s -> { throw exception; }); fakePublisher.publish("one"); fakePublisher.complete(); assertThat(subscribeFuture.isCompletedExceptionally()).isTrue(); assertThatThrownBy(() -> subscribeFuture.get(5, TimeUnit.SECONDS)) .isInstanceOf(ExecutionException.class) .hasCause(exception); } @Test public void filterHandlesError() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); RuntimeException exception = new IllegalArgumentException("Failure!"); CompletableFuture<Void> subscribeFuture = fakePublisher.filter(s -> { throw exception; }).subscribe(r -> {}); fakePublisher.publish("one"); fakePublisher.complete(); assertThat(subscribeFuture.isCompletedExceptionally()).isTrue(); assertThatThrownBy(() -> subscribeFuture.get(5, TimeUnit.SECONDS)) .isInstanceOf(ExecutionException.class) .hasCause(exception); } @Test public void flatMapIterableHandlesError() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); RuntimeException exception = new IllegalArgumentException("Failure!"); CompletableFuture<Void> subscribeFuture = fakePublisher.flatMapIterable(s -> { throw exception; }).subscribe(r -> {}); fakePublisher.publish("one"); fakePublisher.complete(); assertThat(subscribeFuture.isCompletedExceptionally()).isTrue(); assertThatThrownBy(() -> subscribeFuture.get(5, TimeUnit.SECONDS)) .isInstanceOf(ExecutionException.class) .hasCause(exception); } @Test public void addTrailingData_handlesCorrectly() { FakeSdkPublisher<String> fakePublisher = new FakeSdkPublisher<>(); FakeStringSubscriber fakeSubscriber = new FakeStringSubscriber(); fakePublisher.addTrailingData(() -> Arrays.asList("two", "three")) .subscribe(fakeSubscriber); fakePublisher.publish("one"); fakePublisher.complete(); assertThat(fakeSubscriber.recordedEvents()).containsExactly("one", "two", "three"); assertThat(fakeSubscriber.isComplete()).isTrue(); assertThat(fakeSubscriber.isError()).isFalse(); } private final static class FakeByteBufferSubscriber implements Subscriber<ByteBuffer> { private final List<String> recordedEvents = new ArrayList<>(); @Override public void onSubscribe(Subscription s) { } @Override public void onNext(ByteBuffer byteBuffer) { String s = StandardCharsets.UTF_8.decode(byteBuffer).toString(); recordedEvents.add(s); } @Override public void onError(Throwable t) { } @Override public void onComplete() { } public List<String> recordedEvents() { return this.recordedEvents; } } private final static class FakeStringSubscriber implements Subscriber<String> { private final List<String> recordedEvents = new ArrayList<>(); private final List<Throwable> recordedErrors = new ArrayList<>(); private boolean isComplete = false; private boolean isError = false; @Override public void onSubscribe(Subscription s) { s.request(1000); } @Override public void onNext(String s) { recordedEvents.add(s); } @Override public void onError(Throwable t) { recordedErrors.add(t); this.isError = true; } @Override public void onComplete() { this.isComplete = true; } public List<String> recordedEvents() { return this.recordedEvents; } public List<Throwable> recordedErrors() { return this.recordedErrors; } public boolean isComplete() { return isComplete; } public boolean isError() { return isError; } } }
1,644
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/SingleByteArrayAsyncRequestProviderTckTest.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.core.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.tck.TestEnvironment; public class SingleByteArrayAsyncRequestProviderTckTest extends org.reactivestreams.tck.PublisherVerification<ByteBuffer> { public SingleByteArrayAsyncRequestProviderTckTest() { super(new TestEnvironment()); } @Override public long maxElementsFromPublisher() { int canOnlySignalSingleElement = 1; return canOnlySignalSingleElement; } @Override public Publisher<ByteBuffer> createPublisher(long n) { return AsyncRequestBody.fromString("Hello world"); } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } }
1,645
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/async/ChecksumValidatingPublisherTest.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.core.async; import org.junit.BeforeClass; import org.junit.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.async.ChecksumValidatingPublisher; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; /** * Unit test for ChecksumValidatingPublisher */ public class ChecksumValidatingPublisherTest { public static final String SHA256_OF_HELLO_WORLD = "ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw="; private static byte[] testData; @BeforeClass public static void populateData() { testData = "Hello world".getBytes(StandardCharsets.UTF_8); } @Test public void testSinglePacket() { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, testData.length)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, SdkChecksum.forAlgorithm(Algorithm.SHA256), SHA256_OF_HELLO_WORLD); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(testData)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } @Test public void testTwoPackets() { for (int i = 1; i < testData.length - 1; i++) { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, testData.length)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, SdkChecksum.forAlgorithm(Algorithm.SHA256), SHA256_OF_HELLO_WORLD); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(testData, 0, i)); driver.doOnNext(ByteBuffer.wrap(testData, i, testData.length - i)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } } @Test public void testTinyPackets() { for (int packetSize = 1; packetSize < 2; packetSize++) { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, testData.length)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, SdkChecksum.forAlgorithm(Algorithm.SHA256), SHA256_OF_HELLO_WORLD); p.subscribe(s); int currOffset = 0; while (currOffset < testData.length) { final int toSend = Math.min(packetSize, testData.length - currOffset); driver.doOnNext(ByteBuffer.wrap(testData, currOffset, toSend)); currOffset += toSend; } driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } } @Test public void testUnknownLength() { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, testData.length)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, SdkChecksum.forAlgorithm(Algorithm.SHA256), SHA256_OF_HELLO_WORLD); p.subscribe(s); byte[] randomChecksumData = new byte[testData.length]; System.arraycopy(testData, 0, randomChecksumData, 0, testData.length); for (int i = testData.length; i < randomChecksumData.length; i++) { randomChecksumData[i] = (byte) ((testData[i] + 1) & 0x7f); } driver.doOnNext(ByteBuffer.wrap(randomChecksumData)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } @Test public void checksumValidationFailure_throwsSdkClientException() { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, testData.length)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, SdkChecksum.forAlgorithm(Algorithm.SHA256), "someInvalidData"); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(testData)); driver.doOnComplete(); assertTrue(s.isOnErrorCalled()); assertFalse(s.hasCompleted()); } private class TestSubscriber implements Subscriber<ByteBuffer> { final byte[] expected; final List<ByteBuffer> received; boolean completed; boolean onErrorCalled; TestSubscriber(byte[] expected) { this.expected = expected; this.received = new ArrayList<>(); this.completed = false; } @Override public void onSubscribe(Subscription s) { fail("This method not expected to be invoked"); throw new UnsupportedOperationException("!!!TODO: implement this"); } @Override public void onNext(ByteBuffer buffer) { received.add(buffer); } @Override public void onError(Throwable t) { onErrorCalled = true; } @Override public void onComplete() { int matchPos = 0; for (ByteBuffer buffer : received) { byte[] bufferData = new byte[buffer.limit() - buffer.position()]; buffer.get(bufferData); assertArrayEquals(Arrays.copyOfRange(expected, matchPos, matchPos + bufferData.length), bufferData); matchPos += bufferData.length; } assertEquals(expected.length, matchPos); completed = true; } public boolean hasCompleted() { return completed; } public boolean isOnErrorCalled() { return onErrorCalled; } } private class TestPublisher implements Publisher<ByteBuffer> { Subscriber<? super ByteBuffer> s; @Override public void subscribe(Subscriber<? super ByteBuffer> s) { this.s = s; } public void doOnNext(ByteBuffer b) { s.onNext(b); } public void doOnComplete() { s.onComplete(); } } }
1,646
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/io/ChecksumValidatingInputStreamTest.java
package software.amazon.awssdk.core.io; import org.assertj.core.api.Assertions; import org.junit.Test; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.io.ChecksumValidatingInputStream; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class ChecksumValidatingInputStreamTest { @Test public void validCheckSumMatch() throws IOException { String initialString = "Hello world"; InputStream targetStream = new ByteArrayInputStream(initialString.getBytes()); SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.SHA256); ChecksumValidatingInputStream checksumValidatingInputStream = new ChecksumValidatingInputStream(targetStream, sdkChecksum, "ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw="); Assertions.assertThat(readAsStrings(checksumValidatingInputStream)).isEqualTo("Hello world"); } @Test public void validCheckSumMismatch() { String initialString = "Hello world"; InputStream targetStream = new ByteArrayInputStream(initialString.getBytes()); SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.SHA256); ChecksumValidatingInputStream checksumValidatingInputStream = new ChecksumValidatingInputStream(targetStream, sdkChecksum, "ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfz1="); Assertions.assertThatExceptionOfType(SdkClientException.class) .isThrownBy(() ->readAsStrings(checksumValidatingInputStream)); } private String readAsStrings(ChecksumValidatingInputStream checksumValidatingInputStream) throws IOException { StringBuilder textBuilder = new StringBuilder(); try (Reader reader = new BufferedReader(new InputStreamReader (checksumValidatingInputStream, Charset.forName(StandardCharsets.UTF_8.name())))) { int c = 0; while ((c = reader.read()) != -1) { textBuilder.append((char) c); } } return textBuilder.toString(); } }
1,647
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/runtime
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/runtime/transform/SyncStreamingRequestMarshallerTest.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.core.runtime.transform; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.net.URI; 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.core.sync.RequestBody; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * Currently RequestBody always require content length. So we always sent content-length header for all sync APIs. * So this test class only tests the case when content length is present */ @RunWith(MockitoJUnitRunner.class) public class SyncStreamingRequestMarshallerTest { private static final Object object = new Object(); @Mock private Marshaller delegate; private SdkHttpFullRequest request = generateBasicRequest(); @Before public void setup() { when(delegate.marshall(any())).thenReturn(request); } @Test public void contentLengthHeaderIsSet_IfPresent() { String text = "foobar"; StreamingRequestMarshaller marshaller = createMarshaller(RequestBody.fromString(text), true, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, text.length()); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); } @Test public void contentLengthHeaderIsSet_forEmptyContent() { StreamingRequestMarshaller marshaller = createMarshaller(RequestBody.empty(), true, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, 0L); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); } private void assertContentLengthValue(SdkHttpFullRequest httpFullRequest, long value) { assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH).get()) .contains(Long.toString(value)); } private StreamingRequestMarshaller createMarshaller(RequestBody requestBody, boolean requiresLength, boolean transferEncoding, boolean useHttp2) { return StreamingRequestMarshaller.builder() .delegateMarshaller(delegate) .requestBody(requestBody) .requiresLength(requiresLength) .transferEncoding(transferEncoding) .useHttp2(useHttp2) .build(); } private SdkHttpFullRequest generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build(); } }
1,648
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/runtime
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/runtime/transform/AsyncStreamingRequestMarshallerTest.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.core.runtime.transform; 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.when; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.Optional; 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.core.async.AsyncRequestBody; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; @RunWith(MockitoJUnitRunner.class) public class AsyncStreamingRequestMarshallerTest { private static final Object object = new Object(); @Mock private Marshaller delegate; @Mock private AsyncRequestBody requestBody; private SdkHttpFullRequest request = generateBasicRequest(); @Before public void setup() { when(delegate.marshall(any())).thenReturn(request); } @Test public void contentLengthIsPresent_shouldNotOverride() { long contentLengthOnRequest = 1L; long contengLengthOnRequestBody = 5L; when(requestBody.contentLength()).thenReturn(Optional.of(contengLengthOnRequestBody)); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, true, true); SdkHttpFullRequest requestWithContentLengthHeader = generateBasicRequest().toBuilder() .appendHeader(Header.CONTENT_LENGTH, String.valueOf(contentLengthOnRequest)) .build(); when(delegate.marshall(any())).thenReturn(requestWithContentLengthHeader); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, contentLengthOnRequest); } @Test public void contentLengthOnRequestBody_shouldAddContentLengthHeader() { long value = 5L; when(requestBody.contentLength()).thenReturn(Optional.of(value)); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isPresent(); assertContentLengthValue(httpFullRequest, value); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); } @Test public void throwsException_contentLengthHeaderIsMissing_AndRequiresLengthIsPresent() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, false, false); assertThatThrownBy(() -> marshaller.marshall(object)).isInstanceOf(SdkClientException.class); } @Test public void transferEncodingIsUsed_OverHttp1() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(false, true, false); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isEmpty(); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isPresent(); } @Test public void transferEncodingIsNotUsed_OverHttp2() { when(requestBody.contentLength()).thenReturn(Optional.empty()); AsyncStreamingRequestMarshaller marshaller = createMarshaller(false, true, true); SdkHttpFullRequest httpFullRequest = marshaller.marshall(object); assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH)).isEmpty(); assertThat(httpFullRequest.firstMatchingHeader(Header.TRANSFER_ENCODING)).isEmpty(); } private void assertContentLengthValue(SdkHttpFullRequest httpFullRequest, long value) { assertThat(httpFullRequest.firstMatchingHeader(Header.CONTENT_LENGTH).get()) .contains(Long.toString(value)); } private AsyncStreamingRequestMarshaller createMarshaller(boolean requiresLength, boolean transferEncoding, boolean useHttp2) { return AsyncStreamingRequestMarshaller.builder() .delegateMarshaller(delegate) .asyncRequestBody(requestBody) .requiresLength(requiresLength) .transferEncoding(transferEncoding) .useHttp2(useHttp2) .build(); } private SdkHttpFullRequest generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build(); } }
1,649
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/metrics/ErrorTypeTest.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.core.internal.metrics; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; public class ErrorTypeTest { @ParameterizedTest @MethodSource("testCases") public void fromException_mapsToCorrectType(TestCase tc) { assertThat(SdkErrorType.fromException(tc.thrown)).isEqualTo(tc.expectedType); } private static Stream<? extends TestCase> testCases() { return Stream.of( tc(new IOException("I/O"), SdkErrorType.IO), tc(TestServiceException.builder().build(), SdkErrorType.SERVER_ERROR), tc(TestServiceException.builder().throttling(true).build(), SdkErrorType.THROTTLING), tc(ApiCallAttemptTimeoutException.builder().message("Attempt timeout").build(), SdkErrorType.CONFIGURED_TIMEOUT), tc(ApiCallTimeoutException.builder().message("Call timeout").build(), SdkErrorType.CONFIGURED_TIMEOUT), tc(SdkClientException.create("Unmarshalling error"), SdkErrorType.OTHER), tc(new OutOfMemoryError("OOM"), SdkErrorType.OTHER) ); } private static TestCase tc(Throwable thrown, SdkErrorType expectedType) { return new TestCase(thrown, expectedType); } private static class TestCase { private final Throwable thrown; private final SdkErrorType expectedType; public TestCase(Throwable thrown, SdkErrorType expectedType) { this.thrown = thrown; this.expectedType = expectedType; } } private static class TestServiceException extends SdkServiceException { private final boolean throttling; protected TestServiceException(BuilderImpl b) { super(b); this.throttling = b.throttling; } @Override public boolean isThrottlingException() { return throttling; } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkServiceException.Builder { Builder throttling(Boolean throttling); @Override TestServiceException build(); } public static class BuilderImpl extends SdkServiceException.BuilderImpl implements Builder { private boolean throttling; @Override public boolean equalsBySdkFields(Object other) { return super.equalsBySdkFields(other); } @Override public Builder throttling(Boolean throttling) { this.throttling = throttling; return this; } @Override public TestServiceException build() { return new TestServiceException(this); } } } }
1,650
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/retry/RateLimitingTokenBucketEndToEndTest.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.core.internal.retry; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.assertj.core.data.Offset; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * From the spec: * * The new_token_bucket_rate is the expected value that should be passed to the _TokenBucketUpdateRate() at the end of * _UpdateClientSendingRate(). The measured_tx_rate value is the measured client sending rate calculated from * _UpdateMeasuredRate(). * * Note: per spec owner, "new_token_bucket_rate" above is supposed to be "fill_rate" instead. */ @RunWith(Parameterized.class) public class RateLimitingTokenBucketEndToEndTest { private static final double EPSILON = 1E-6; private static final TestClock TEST_CLOCK = new TestClock(); private static final RateLimitingTokenBucket TOKEN_BUCKET = new RateLimitingTokenBucket(TEST_CLOCK); @Parameterized.Parameter public TestCase testCase; @Parameterized.Parameters(name = "{0}") public static Iterable<TestCase> testCases() { return Arrays.asList( new TestCase().withTimestamp(0.2).withMeasuredTxRate(0.000000).withExpectedNewFillRate(0.500000), new TestCase().withTimestamp(0.4).withMeasuredTxRate(0.000000).withExpectedNewFillRate(0.500000), new TestCase().withTimestamp(0.6).withMeasuredTxRate(4.800000).withExpectedNewFillRate(0.500000), new TestCase().withTimestamp(0.8).withMeasuredTxRate(4.800000).withExpectedNewFillRate(0.500000), new TestCase().withTimestamp(1.0).withMeasuredTxRate(4.160000).withExpectedNewFillRate(0.500000), new TestCase().withTimestamp(1.2).withMeasuredTxRate(4.160000).withExpectedNewFillRate(0.691200), new TestCase().withTimestamp(1.4).withMeasuredTxRate(4.160000).withExpectedNewFillRate(1.097600), new TestCase().withTimestamp(1.6).withMeasuredTxRate(5.632000).withExpectedNewFillRate(1.638400), new TestCase().withTimestamp(1.8).withMeasuredTxRate(5.632000).withExpectedNewFillRate(2.332800), new TestCase().withThrottled(true).withTimestamp(2.0).withMeasuredTxRate(4.326400).withExpectedNewFillRate(3.028480), new TestCase().withTimestamp(2.2).withMeasuredTxRate(4.326400).withExpectedNewFillRate(3.486639), new TestCase().withTimestamp(2.4).withMeasuredTxRate(4.326400).withExpectedNewFillRate(3.821874), new TestCase().withTimestamp(2.6).withMeasuredTxRate(5.665280).withExpectedNewFillRate(4.053386), new TestCase().withTimestamp(2.8).withMeasuredTxRate(5.665280).withExpectedNewFillRate(4.200373), new TestCase().withTimestamp(3.0).withMeasuredTxRate(4.333056).withExpectedNewFillRate(4.282037), new TestCase().withThrottled(true).withTimestamp(3.2).withMeasuredTxRate(4.333056).withExpectedNewFillRate(2.997426), new TestCase().withTimestamp(3.4).withMeasuredTxRate(4.333056).withExpectedNewFillRate(3.452226) ); } @Test public void testCalculatesCorrectFillRate() { TEST_CLOCK.setTime(testCase.timestamp); TOKEN_BUCKET.updateClientSendingRate(testCase.throttled); assertThat(TOKEN_BUCKET.getFillRate()) .withFailMessage("The calculated fill rate is not within error of the expected value") .isCloseTo(testCase.expectedNewFillRate, Offset.offset(EPSILON)); assertThat(TOKEN_BUCKET.getMeasuredTxRate()) .withFailMessage("The calculated tx rate is not within error of the expected value") .isCloseTo(testCase.measuredTxRate, Offset.offset(EPSILON)); } private static class TestCase { private boolean throttled; private double timestamp; private double measuredTxRate; private double expectedNewFillRate; public TestCase withThrottled(boolean throttled) { this.throttled = throttled; return this; } public TestCase withTimestamp(double timestamp) { this.timestamp = timestamp; return this; } public TestCase withMeasuredTxRate(double measuredTxRate) { this.measuredTxRate = measuredTxRate; return this; } public TestCase withExpectedNewFillRate(double expectedNewFillRate) { this.expectedNewFillRate = expectedNewFillRate; return this; } @Override public String toString() { return "TestCase{" + "throttled=" + throttled + ", timestamp=" + timestamp + ", measuredTxRate=" + measuredTxRate + ", expectedNewFillRate=" + expectedNewFillRate + '}'; } } private static class TestClock implements RateLimitingTokenBucket.Clock { private double time = 0; public void setTime(double time) { this.time = time; } @Override public double time() { return time; } } }
1,651
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/retry/RateLimitingTokenBucketCubicTest.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.core.internal.retry; import static org.assertj.core.api.Java6Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.assertj.core.data.Offset; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class RateLimitingTokenBucketCubicTest { private static final double EPSILON = 1E-6; @Parameterized.Parameter public TestCaseGroup testCaseGroup; @Parameterized.Parameters(name = "{0}") public static Iterable<TestCaseGroup> testCases() { return Arrays.asList( new TestCaseGroup() .withName("All success") .withLastMaxRate(10) .withLastThrottleTime(5) .withTestCases( new TestCase().withTimestamp(5).withExpectedCalculatedRate(7.0), new TestCase().withTimestamp(6).withExpectedCalculatedRate(9.64893600966), new TestCase().withTimestamp(7).withExpectedCalculatedRate(10.000030849917364), new TestCase().withTimestamp(8).withExpectedCalculatedRate(10.453284520772092), new TestCase().withTimestamp(9).withExpectedCalculatedRate(13.408697022224185), new TestCase().withTimestamp(10).withExpectedCalculatedRate(21.26626835427364), new TestCase().withTimestamp(11).withExpectedCalculatedRate(36.425998516920465) ), new TestCaseGroup() .withName("Mixed") .withLastMaxRate(10) .withLastThrottleTime(5) .withTestCases( new TestCase().withTimestamp(5).withExpectedCalculatedRate(7.0), new TestCase().withTimestamp(6).withExpectedCalculatedRate(9.64893600966), new TestCase().withTimestamp(7).withThrottled(true).withExpectedCalculatedRate(6.754255206761999), new TestCase().withTimestamp(8).withThrottled(true).withExpectedCalculatedRate(4.727978644733399), new TestCase().withTimestamp(9).withExpectedCalculatedRate(6.606547753887045), new TestCase().withTimestamp(10).withExpectedCalculatedRate(6.763279816944947), new TestCase().withTimestamp(11).withExpectedCalculatedRate(7.598174833907107), new TestCase().withTimestamp(12).withExpectedCalculatedRate(11.511232804773524) ) ); } @Test public void calculatesCorrectRate() { // Prime the token bucket for the initial test case RateLimitingTokenBucket tb = new RateLimitingTokenBucket(); tb.setLastMaxRate(testCaseGroup.lastMaxRate); tb.setLastThrottleTime(testCaseGroup.lastThrottleTime); tb.calculateTimeWindow(); // Note: No group starts with a throttled case, so we never actually // use this value; just to make the compiler happy. double lastCalculatedRate = Double.NEGATIVE_INFINITY; for (TestCase tc :testCaseGroup.testCases) { if (tc.throttled) { tb.setLastMaxRate(lastCalculatedRate); tb.calculateTimeWindow(); tb.setLastThrottleTime(tc.timestamp); lastCalculatedRate = tb.cubicThrottle(lastCalculatedRate); } else { tb.calculateTimeWindow(); lastCalculatedRate = tb.cubicSuccess(tc.timestamp); } assertThat(lastCalculatedRate).isCloseTo(tc.expectedCalculatedRate, Offset.offset(EPSILON)); } } private static class TestCaseGroup { private String name; private double lastMaxRate; private double lastThrottleTime; private List<TestCase> testCases; public TestCaseGroup withName(String name) { this.name = name; return this; } public TestCaseGroup withLastMaxRate(double lastMaxRate) { this.lastMaxRate = lastMaxRate; return this; } public TestCaseGroup withLastThrottleTime(double lastThrottleTime) { this.lastThrottleTime = lastThrottleTime; return this; } public TestCaseGroup withTestCases(TestCase... testCases) { this.testCases = Arrays.asList(testCases); return this; } @Override public String toString() { return name; } } private static class TestCase { private boolean throttled; private double timestamp; private double expectedCalculatedRate; public TestCase withThrottled(boolean throttled) { this.throttled = throttled; return this; } public TestCase withTimestamp(double timestamp) { this.timestamp = timestamp; return this; } public TestCase withExpectedCalculatedRate(double expectedCalculatedRate) { this.expectedCalculatedRate = expectedCalculatedRate; return this; } } }
1,652
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/retry/ClockSkewAdjusterTest.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.core.internal.retry; import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.MINUTES; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; import java.time.Instant; import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.DateUtils; public class ClockSkewAdjusterTest { private ClockSkewAdjuster adjuster = new ClockSkewAdjuster(); @Test public void adjustmentTranslatesCorrectly() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(1, HOURS))).isCloseTo(-1 * 60 * 60, within(5)); assertThat(adjuster.getAdjustmentInSeconds(responseWithDateOffset(-14, MINUTES))).isCloseTo(14 * 60, within(5)); } @Test public void farFutureDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("Fri, 31 Dec 9999 23:59:59 GMT"))).isEqualTo(0); } @Test public void badDateTranslatesToZero() { assertThat(adjuster.getAdjustmentInSeconds(responseWithDate("X"))).isEqualTo(0); } private SdkHttpFullResponse responseWithDateOffset(int value, ChronoUnit unit) { return SdkHttpFullResponse.builder() .putHeader("Date", DateUtils.formatRfc822Date(Instant.now().plus(value, unit))) .build(); } private SdkHttpFullResponse responseWithDate(String date) { return SdkHttpFullResponse.builder() .putHeader("Date", date) .build(); } }
1,653
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/retry/RateLimitingTokenBucketTest.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.core.internal.retry; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class RateLimitingTokenBucketTest { @Test public void acquire_notEnabled_returnsTrue() { RateLimitingTokenBucket tb = new RateLimitingTokenBucket(); assertThat(tb.acquire(0.0)).isTrue(); } @Test public void acquire_capacitySufficient_returnsImmediately() { RateLimitingTokenBucket tb = Mockito.spy(new RateLimitingTokenBucket()); // stub out refill() so we have control over the capacity Mockito.doAnswer(invocationOnMock -> null).when(tb).refill(); tb.setFillRate(0.5); tb.setCurrentCapacity(1000.0); tb.enable(); long a = System.nanoTime(); boolean acquired = tb.acquire(1000.0); long elapsed = System.nanoTime() - a; assertThat(acquired).isTrue(); assertThat(TimeUnit.NANOSECONDS.toMillis(elapsed)).isLessThan(3L); } @Test public void acquire_capacityInsufficient_sleepsForRequiredTime() { RateLimitingTokenBucket tb = Mockito.spy(new RateLimitingTokenBucket()); // stub out refill() so we have control over the capacity Mockito.doAnswer(invocationOnMock -> null).when(tb).refill(); tb.setFillRate(1.0); tb.setCurrentCapacity(0.0); tb.enable(); // 1 token to wait for at a rate of 1 per second should sleep for approx 1s long a = System.nanoTime(); boolean acquired = tb.acquire(1); long elapsed = System.nanoTime() - a; assertThat(acquired).isTrue(); assertThat(tb.getCurrentCapacity()).isNegative(); assertThat(tb.getCurrentCapacity()).isEqualTo(-1.0); assertThat(Duration.ofNanos(elapsed).getSeconds()).isEqualTo(1); } @Test public void acquire_capacityInsufficient_fastFailEnabled_doesNotSleep() { RateLimitingTokenBucket tb = Mockito.spy(new RateLimitingTokenBucket()); // stub out refill() so we have control over the capacity Mockito.doAnswer(invocationOnMock -> null).when(tb).refill(); tb.setFillRate(1.0); tb.setCurrentCapacity(4.0); tb.enable(); long a = System.nanoTime(); boolean acquired = tb.acquire(5, true); long elapsed = System.nanoTime() - a; assertThat(acquired).isFalse(); assertThat(tb.getCurrentCapacity()).isEqualTo(4.0); // The method call should be nowhere near a millisecond assertThat(Duration.ofNanos(elapsed).getSeconds()).isZero(); } @Test public void tryAcquireCapacity_capacitySufficient_returns0() { RateLimitingTokenBucket tb = new RateLimitingTokenBucket(); tb.setCurrentCapacity(5.0); assertThat(tb.tryAcquireCapacity(5.0)).isZero(); assertThat(tb.getCurrentCapacity()).isZero(); } @Test public void tryAcquireCapacity_amountGreaterThanCapacity_returnsNonZero() { RateLimitingTokenBucket tb = new RateLimitingTokenBucket(); tb.setCurrentCapacity(5.0); assertThat(tb.tryAcquireCapacity(8.0)).isEqualTo(3); assertThat(tb.getCurrentCapacity()).isNegative(); assertThat(tb.getCurrentCapacity()).isEqualTo(-3); } @Test public void acquire_amountGreaterThanNonZeroPositiveCapacity_setsNegativeCapacity() { RateLimitingTokenBucket tb = Mockito.spy(new RateLimitingTokenBucket()); // stub out sleep , since we do not actually want to wait for sleep time Mockito.doAnswer(invocationOnMock -> null).when(tb).sleep(2); tb.setFillRate(1.0); tb.setCurrentCapacity(1.0); tb.enable(); boolean acquired = tb.acquire(3.0); assertThat(acquired).isTrue(); assertThat(tb.getCurrentCapacity()).isNegative(); assertThat(tb.getCurrentCapacity()).isEqualTo(-2.0); } @Test public void acquire_amountGreaterThanNegativeCapacity_setsNegativeCapacity() { RateLimitingTokenBucket tb = Mockito.spy(new RateLimitingTokenBucket()); // stub out sleep , since we do not actually want to wait for sleep time Mockito.doAnswer(invocationOnMock -> null).when(tb).sleep(3); tb.setFillRate(1.0); tb.setCurrentCapacity(-1.0); tb.enable(); boolean acquired = tb.acquire(2.0); assertThat(acquired).isTrue(); assertThat(tb.getCurrentCapacity()).isNegative(); assertThat(tb.getCurrentCapacity()).isEqualTo(-3.0); } @Test public void tryAcquireCapacity_capacityInsufficient_returnsDifference() { RateLimitingTokenBucket tb = new RateLimitingTokenBucket(); tb.setCurrentCapacity(3.0); assertThat(tb.tryAcquireCapacity(5.0)).isEqualTo(2.0); } }
1,654
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/MimetypeTest.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.core.internal.util; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.nio.file.Path; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class MimetypeTest { private static Mimetype mimetype; @BeforeAll public static void setup() { mimetype = Mimetype.getInstance(); } @Test public void extensionsWithCaps() throws Exception { assertThat(mimetype.getMimetype("image.JPeG")).isEqualTo("image/jpeg"); } @Test public void extensionsWithUvi() throws Exception { assertThat(mimetype.getMimetype("test.uvvi")).isEqualTo("image/vnd.dece.graphic"); } @Test public void unknownExtensions_defaulttoBeStream() throws Exception { assertThat(mimetype.getMimetype("test.unknown")).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void noExtensions_defaulttoBeStream() throws Exception { assertThat(mimetype.getMimetype("test")).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void pathWithoutFileName_defaulttoBeStream() throws Exception { Path mockPath = mock(Path.class); when(mockPath.getFileName()).thenReturn(null); assertThat(mimetype.getMimetype(mockPath)).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } }
1,655
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/MetricUtilsTest.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.core.internal.util; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.IOException; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.utils.Pair; public class MetricUtilsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void measureDuration_returnsAccurateDurationInformation() { long testDurationNanos = Duration.ofMillis(1).toNanos(); Pair<Object, Duration> measuredExecute = MetricUtils.measureDuration(() -> { long start = System.nanoTime(); // spin thread instead of Thread.sleep() for a bit more accuracy... while (System.nanoTime() - start < testDurationNanos) { } return "foo"; }); assertThat(measuredExecute.right()).isGreaterThanOrEqualTo(Duration.ofNanos(testDurationNanos)); } @Test public void measureDuration_returnsCallableReturnValue() { String result = "foo"; Pair<String, Duration> measuredExecute = MetricUtils.measureDuration(() -> result); assertThat(measuredExecute.left()).isEqualTo(result); } @Test public void measureDurationUnsafe_doesNotWrapException() throws Exception { IOException ioe = new IOException("boom"); thrown.expect(IOException.class); try { MetricUtils.measureDurationUnsafe(() -> { throw ioe; }); } catch (IOException caught) { assertThat(caught).isSameAs(ioe); throw caught; } } @Test public void measureDuration_doesNotWrapException() { RuntimeException e = new RuntimeException("boom"); thrown.expect(RuntimeException.class); try { MetricUtils.measureDuration(() -> { throw e; }); } catch (RuntimeException caught) { assertThat(caught).isSameAs(e); throw caught; } } @Test public void reportDuration_completableFuture_reportsAccurateDurationInformation() { MetricCollector mockCollector = mock(MetricCollector.class); SdkMetric<Duration> mockMetric = mock(SdkMetric.class); CompletableFuture<String> future = new CompletableFuture<>(); CompletableFuture<String> result = MetricUtils.reportDuration(() -> future, mockCollector, mockMetric); long testDurationNanos = Duration.ofMillis(1).toNanos(); long start = System.nanoTime(); // spin thread instead of Thread.sleep() for a bit more accuracy... while (System.nanoTime() - start < testDurationNanos) { } future.complete("foo"); future.join(); ArgumentCaptor<Duration> duration = ArgumentCaptor.forClass(Duration.class); verify(mockCollector).reportMetric(eq(mockMetric), duration.capture()); assertThat(duration.getValue()).isGreaterThanOrEqualTo(Duration.ofNanos(testDurationNanos)); } @Test public void reportDuration_completableFuture_completesExceptionally_reportsAccurateDurationInformation() { MetricCollector mockCollector = mock(MetricCollector.class); SdkMetric<Duration> mockMetric = mock(SdkMetric.class); CompletableFuture<String> future = new CompletableFuture<>(); CompletableFuture<String> result = MetricUtils.reportDuration(() -> future, mockCollector, mockMetric); long testDurationNanos = Duration.ofMillis(1).toNanos(); long start = System.nanoTime(); // spin thread instead of Thread.sleep() for a bit more accuracy... while (System.nanoTime() - start < testDurationNanos) { } future.completeExceptionally(new RuntimeException("future failed")); try { future.join(); } catch (CompletionException e) { ArgumentCaptor<Duration> duration = ArgumentCaptor.forClass(Duration.class); verify(mockCollector).reportMetric(eq(mockMetric), duration.capture()); assertThat(duration.getValue()).isGreaterThanOrEqualTo(Duration.ofNanos(testDurationNanos)); } } @Test public void reportDuration_completableFuture_returnsCallableReturnValue() { MetricCollector mockCollector = mock(MetricCollector.class); SdkMetric<Duration> mockMetric = mock(SdkMetric.class); CompletableFuture<String> future = new CompletableFuture<>(); CompletableFuture<String> result = MetricUtils.reportDuration(() -> future, mockCollector, mockMetric); assertThat(result).isEqualTo(result); } @Test public void reportDuration_completableFuture_doesNotWrapException() { MetricCollector mockCollector = mock(MetricCollector.class); SdkMetric<Duration> mockMetric = mock(SdkMetric.class); RuntimeException e = new RuntimeException("boom"); thrown.expect(RuntimeException.class); try { MetricUtils.reportDuration(() -> { throw e; }, mockCollector, mockMetric); } catch (RuntimeException caught) { assertThat(caught).isSameAs(e); throw caught; } } @Test public void collectHttpMetrics_collectsAllExpectedMetrics() { MetricCollector mockCollector = mock(MetricCollector.class); int statusCode = 200; String requestId = "request-id"; String amznRequestId = "amzn-request-id"; String requestId2 = "request-id-2"; SdkHttpFullResponse response = SdkHttpFullResponse.builder() .statusCode(statusCode) .putHeader("x-amz-request-id", requestId) .putHeader(HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER, amznRequestId) .putHeader(HttpResponseHandler.X_AMZ_ID_2_HEADER, requestId2) .build(); MetricUtils.collectHttpMetrics(mockCollector, response); verify(mockCollector).reportMetric(HttpMetric.HTTP_STATUS_CODE, statusCode); verify(mockCollector).reportMetric(CoreMetric.AWS_REQUEST_ID, requestId); verify(mockCollector).reportMetric(CoreMetric.AWS_REQUEST_ID, amznRequestId); verify(mockCollector).reportMetric(CoreMetric.AWS_EXTENDED_REQUEST_ID, requestId2); } }
1,656
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/AsyncResponseHandlerTestUtils.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.core.internal.util; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.async.DrainingSubscriber; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.internal.http.async.CombinedResponseAsyncHttpResponseHandler; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpResponse; public class AsyncResponseHandlerTestUtils { private AsyncResponseHandlerTestUtils() { } public static <T> TransformingAsyncResponseHandler<T> noOpResponseHandler() { return noOpResponseHandler(null); } public static <T> TransformingAsyncResponseHandler<T> noOpResponseHandler(T result) { return new NoOpResponseHandler<>(result); } public static <T> TransformingAsyncResponseHandler<T> superSlowResponseHandler(long sleepInMillis) { return superSlowResponseHandler(null, sleepInMillis); } public static <T> TransformingAsyncResponseHandler<T> superSlowResponseHandler(T result, long sleepInMillis) { return new SuperSlowResponseHandler<>(result, sleepInMillis); } public static <T> TransformingAsyncResponseHandler<Response<T>> combinedAsyncResponseHandler( TransformingAsyncResponseHandler<T> successResponseHandler, TransformingAsyncResponseHandler<? extends SdkException> failureResponseHandler) { return new CombinedResponseAsyncHttpResponseHandler<>( successResponseHandler == null ? noOpResponseHandler() : successResponseHandler, failureResponseHandler == null ? noOpResponseHandler() : failureResponseHandler); } private static class NoOpResponseHandler<T> implements TransformingAsyncResponseHandler<T> { private final CompletableFuture<T> cf = new CompletableFuture<>(); private final T result; NoOpResponseHandler(T result) { this.result = result; } @Override public CompletableFuture<T> prepare() { return cf; } @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { stream.subscribe(new DrainingSubscriber<ByteBuffer>() { @Override public void onError(Throwable t) { cf.completeExceptionally(t); } @Override public void onComplete() { cf.complete(result); } }); } @Override public void onError(Throwable error) { cf.completeExceptionally(error); } } private static class SuperSlowResponseHandler<T> implements TransformingAsyncResponseHandler<T> { private final CompletableFuture<T> cf = new CompletableFuture<>(); private final T result; private final long sleepMillis; SuperSlowResponseHandler(T result, long sleepMillis) { this.result = result; this.sleepMillis = sleepMillis; } @Override public CompletableFuture<T> prepare() { return cf.thenApply(r -> { try { Thread.sleep(sleepMillis); } catch (InterruptedException ignored) { } return r; }); } @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { stream.subscribe(new DrainingSubscriber<ByteBuffer>() { @Override public void onError(Throwable t) { cf.completeExceptionally(t); } @Override public void onComplete() { cf.complete(result); } }); } @Override public void onError(Throwable error) { cf.completeExceptionally(error); } } }
1,657
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/HttpChecksumResolverTest.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.core.internal.util; import java.net.URI; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; public class HttpChecksumResolverTest { HttpChecksum CRC32_STREAMING_CHECKSUM = HttpChecksum.builder() .requestChecksumRequired(true) .responseAlgorithms("crc32c", "crc32") .requestAlgorithm("crc32") .requestValidationMode("ENABLED").build(); @Test public void testResolvedChecksumSpecsWithAllTraitsSet() { ExecutionAttributes executionAttributes = getExecutionAttributeWithAllFieldsSet(); ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); ChecksumSpecs expectedChecksum = ChecksumSpecs.builder() .isValidationEnabled(true) .isRequestChecksumRequired(true) .headerName("x-amz-checksum-crc32") .algorithm(Algorithm.CRC32) .responseValidationAlgorithms(Arrays.asList(Algorithm.CRC32C, Algorithm.CRC32)) .build(); Assert.assertEquals(expectedChecksum, resolvedChecksumSpecs); } private ExecutionAttributes getExecutionAttributeWithAllFieldsSet() { return ExecutionAttributes.builder().put( SdkInternalExecutionAttribute.HTTP_CHECKSUM, CRC32_STREAMING_CHECKSUM).build(); } @Test public void testResolvedChecksumSpecsWithOnlyHttpChecksumRequired() { ExecutionAttributes executionAttributes = ExecutionAttributes.builder().put( SdkInternalExecutionAttribute.HTTP_CHECKSUM, HttpChecksum.builder() .requestChecksumRequired(true) .build()).build(); ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); ChecksumSpecs expectedChecksum = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .build(); Assert.assertEquals(expectedChecksum, resolvedChecksumSpecs); } @Test public void testResolvedChecksumSpecsWithDefaults() { ExecutionAttributes executionAttributes = ExecutionAttributes.builder().put( SdkInternalExecutionAttribute.HTTP_CHECKSUM, HttpChecksum.builder().build()).build(); ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); ChecksumSpecs expectedChecksum = ChecksumSpecs.builder() .build(); Assert.assertEquals(expectedChecksum, resolvedChecksumSpecs); } @Test public void headerBasedChecksumAlreadyPresent() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/")) .appendHeader("x-amz-checksum-crc32", "checksum_data") .method(SdkHttpMethod.HEAD) .build(); ExecutionAttributes executionAttributes = getExecutionAttributeWithAllFieldsSet(); ChecksumSpecs checksumSpecs = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null); boolean checksumHeaderAlreadyUpdated = HttpChecksumUtils.isHttpChecksumPresent(sdkRequest, checksumSpecs); Assert.assertTrue(checksumHeaderAlreadyUpdated); } @Test public void headerBasedChecksumWithDifferentHeader() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/")) .appendHeader("x-amz-checksum-sha256", "checksum_data") .method(SdkHttpMethod.HEAD) .build(); ExecutionAttributes executionAttributes = getExecutionAttributeWithAllFieldsSet(); ChecksumSpecs checksumSpecs = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null); boolean checksumHeaderAlreadyUpdated = HttpChecksumUtils.isHttpChecksumPresent(sdkRequest, checksumSpecs); Assert.assertFalse(checksumHeaderAlreadyUpdated); } @Test public void trailerBasedChecksumAlreadyPresent() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/")) .appendHeader("x-amz-trailer", "x-amz-checksum-crc32") .method(SdkHttpMethod.HEAD) .build(); ExecutionAttributes executionAttributes = getExecutionAttributeWithAllFieldsSet(); ChecksumSpecs checksumSpecs = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null); boolean checksumHeaderAlreadyUpdated = HttpChecksumUtils .isHttpChecksumPresent(sdkRequest, checksumSpecs); Assert.assertTrue(checksumHeaderAlreadyUpdated); } @Test public void trailerBasedChecksumWithDifferentTrailerHeader() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/")) .appendHeader("x-amz-trailer", "x-amz-checksum-sha256") .method(SdkHttpMethod.HEAD) .build(); ExecutionAttributes executionAttributes = getExecutionAttributeWithAllFieldsSet(); ChecksumSpecs checksumSpecs = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null); boolean checksumHeaderAlreadyUpdated = HttpChecksumUtils .isHttpChecksumPresent(sdkRequest, checksumSpecs); Assert.assertFalse(checksumHeaderAlreadyUpdated); } }
1,658
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/ResponseHandlerTestUtils.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.core.internal.util; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.internal.http.CombinedResponseHandler; public final class ResponseHandlerTestUtils { private ResponseHandlerTestUtils() { } public static <T> HttpResponseHandler<T> noOpSyncResponseHandler() { return (response, executionAttributes) -> null; } public static HttpResponseHandler<SdkServiceException> superSlowResponseHandler(long sleepInMills) { return (response, executionAttributes) -> { Thread.sleep(sleepInMills); return null; }; } public static <T> HttpResponseHandler<Response<T>> combinedSyncResponseHandler( HttpResponseHandler<T> successResponseHandler, HttpResponseHandler<? extends SdkException> failureResponseHandler) { return new CombinedResponseHandler<>( successResponseHandler == null ? noOpSyncResponseHandler() : successResponseHandler, failureResponseHandler == null ? noOpSyncResponseHandler() : failureResponseHandler); } }
1,659
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/util/CapacityManagerTest.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.core.internal.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Tests the behavior of the {@link CapacityManager} */ public class CapacityManagerTest { /** * Tests that capacity can be acquired when available and can not be * once exhausted. */ @Test public void acquire() { CapacityManager mgr = new CapacityManager(10); assertTrue(mgr.acquire()); assertEquals(mgr.availableCapacity(), 9); assertEquals(mgr.consumedCapacity(), 1); assertTrue(mgr.acquire(9)); assertEquals(mgr.availableCapacity(), 0); assertEquals(mgr.consumedCapacity(), 10); assertFalse(mgr.acquire(1)); } /** * Tests that capacity can be properly released, making additional capacity * available to be acquired. */ @Test public void release() { CapacityManager mgr = new CapacityManager(10); mgr.acquire(10); mgr.release(); assertEquals(mgr.availableCapacity(), 1); assertEquals(mgr.consumedCapacity(), 9); mgr.release(50); assertEquals(mgr.availableCapacity(), 10); assertEquals(mgr.consumedCapacity(), 0); } /** * Tests that, if created with negative capacity, CapacityManager effectively operates * in a no-op mode. */ @Test public void noOp() { CapacityManager mgr = new CapacityManager(-1); assertTrue(mgr.acquire()); mgr.release(); assertTrue(mgr.acquire()); assertEquals(mgr.availableCapacity(), -1); assertEquals(mgr.consumedCapacity(), 0); } }
1,660
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/EnvelopeWrappedSdkPublisherTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.function.BiFunction; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import utils.FakePublisher; @RunWith(MockitoJUnitRunner.class) public class EnvelopeWrappedSdkPublisherTest { private static final BiFunction<String, String, String> CONCAT_STRINGS = (s1, s2) -> s1 + s2; private final FakePublisher<String> fakePublisher = new FakePublisher<>(); @Mock private Subscriber<String> mockSubscriber; @Test public void noPrefixOrSuffix_noEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void noPrefixOrSuffix_singleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void noPrefixOrSuffix_multipleEvents() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test2"); verify(mockSubscriber).onNext("test2"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixOnly_noEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixOnly_singleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test-prefix:test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixOnly_multipleEvents() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", null, CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test-prefix:test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test2"); verify(mockSubscriber).onNext("test2"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void suffixOnly_noEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void suffixOnly_singleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test"); verify(mockSubscriber).onNext("test"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onNext(":test-suffix"); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void suffixOnly_multipleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, null, ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test2"); verify(mockSubscriber).onNext("test2"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onNext(":test-suffix"); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixAndSuffix_noEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixAndSuffix_singleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test"); verify(mockSubscriber).onNext("test-prefix:test"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onNext(":test-suffix"); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void prefixAndSuffix_multipleEvent() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test1"); verify(mockSubscriber).onNext("test-prefix:test1"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.publish("test2"); verify(mockSubscriber).onNext("test2"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); fakePublisher.complete(); verify(mockSubscriber).onNext(":test-suffix"); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void onError() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", ":test-suffix", CONCAT_STRINGS); verifyNoMoreInteractions(mockSubscriber); contentWrappingPublisher.subscribe(mockSubscriber); verify(mockSubscriber, never()).onNext(anyString()); verify(mockSubscriber).onSubscribe(any()); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); RuntimeException exception = new RuntimeException("boom"); fakePublisher.doThrow(exception); verify(mockSubscriber).onError(exception); } @Test public void subscribe_nullSubscriber_throwsNpe() { EnvelopeWrappedSdkPublisher<String> contentWrappingPublisher = EnvelopeWrappedSdkPublisher.of(fakePublisher, "test-prefix:", ":test-suffix", CONCAT_STRINGS); assertThatThrownBy(() -> contentWrappingPublisher.subscribe((Subscriber<String>)null)) .isInstanceOf(NullPointerException.class); } }
1,661
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/SplittingPublisherTestUtils.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.core.internal.async; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.io.File; import java.io.FileInputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.assertj.core.api.Assertions; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.internal.async.ByteArrayAsyncResponseTransformer; import software.amazon.awssdk.core.internal.async.SplittingPublisherTest; public final class SplittingPublisherTestUtils { public static void verifyIndividualAsyncRequestBody(SdkPublisher<AsyncRequestBody> publisher, Path file, int chunkSize) throws Exception { List<CompletableFuture<byte[]>> futures = new ArrayList<>(); publisher.subscribe(requestBody -> { CompletableFuture<byte[]> baosFuture = new CompletableFuture<>(); ByteArrayAsyncResponseTransformer.BaosSubscriber subscriber = new ByteArrayAsyncResponseTransformer.BaosSubscriber(baosFuture); requestBody.subscribe(subscriber); futures.add(baosFuture); }).get(5, TimeUnit.SECONDS); long contentLength = file.toFile().length(); Assertions.assertThat(futures.size()).isEqualTo((int) Math.ceil(contentLength / (double) chunkSize)); for (int i = 0; i < futures.size(); i++) { try (FileInputStream fileInputStream = new FileInputStream(file.toFile())) { byte[] expected; if (i == futures.size() - 1) { int lastChunk = contentLength % chunkSize == 0 ? chunkSize : (int) (contentLength % chunkSize); expected = new byte[lastChunk]; } else { expected = new byte[chunkSize]; } fileInputStream.skip(i * chunkSize); fileInputStream.read(expected); byte[] actualBytes = futures.get(i).join(); Assertions.assertThat(actualBytes).isEqualTo(expected); } } } }
1,662
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/FileAsyncResponseTransformerTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.FileTransformerConfiguration.FailureBehavior.DELETE; import static software.amazon.awssdk.core.FileTransformerConfiguration.FailureBehavior.LEAVE; import com.google.common.jimfs.Jimfs; import io.reactivex.Flowable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.FileTransformerConfiguration; import software.amazon.awssdk.core.FileTransformerConfiguration.FileWriteOption; import software.amazon.awssdk.core.async.SdkPublisher; /** * Tests for {@link FileAsyncResponseTransformer}. */ class FileAsyncResponseTransformerTest { private FileSystem testFs; @BeforeEach public void setup() { testFs = Jimfs.newFileSystem(); } @AfterEach public void teardown() throws IOException { testFs.close(); } @Test public void errorInStream_completesFuture() { Path testPath = testFs.getPath("test_file.txt"); FileAsyncResponseTransformer xformer = new FileAsyncResponseTransformer(testPath); CompletableFuture prepareFuture = xformer.prepare(); xformer.onResponse(new Object()); xformer.onStream(subscriber -> { subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { } @Override public void cancel() { } }); subscriber.onError(new RuntimeException("Something went wrong")); }); assertThat(prepareFuture.isCompletedExceptionally()).isTrue(); } @Test public void synchronousPublisher_shouldNotHang() throws Exception { List<CompletableFuture> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { Path testPath = testFs.getPath(i + "test_file.txt"); FileAsyncResponseTransformer transformer = new FileAsyncResponseTransformer(testPath); CompletableFuture prepareFuture = transformer.prepare(); transformer.onResponse(new Object()); transformer.onStream(testPublisher(RandomStringUtils.randomAlphanumeric(30000))); futures.add(prepareFuture); } CompletableFuture<Void> future = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); future.get(10, TimeUnit.SECONDS); assertThat(future.isCompletedExceptionally()).isFalse(); } @Test void noConfiguration_fileAlreadyExists_shouldThrowException() throws Exception { Path testPath = testFs.getPath("test_file.txt"); Files.write(testPath, RandomStringUtils.random(1000).getBytes(StandardCharsets.UTF_8)); assertThat(testPath).exists(); String content = RandomStringUtils.randomAlphanumeric(30000); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath); CompletableFuture<String> future = transformer.prepare(); transformer.onResponse("foobar"); assertThatThrownBy(() -> transformer.onStream(testPublisher(content))).hasRootCauseInstanceOf(FileAlreadyExistsException.class); } @Test void createOrReplaceExisting_fileDoesNotExist_shouldCreateNewFile() throws Exception { Path testPath = testFs.getPath("test_file.txt"); assertThat(testPath).doesNotExist(); String newContent = RandomStringUtils.randomAlphanumeric(2000); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, FileTransformerConfiguration.defaultCreateOrReplaceExisting()); stubSuccessfulStreaming(newContent, transformer); assertThat(testPath).hasContent(newContent); } @Test void createOrReplaceExisting_fileAlreadyExists_shouldReplaceExisting() throws Exception { Path testPath = testFs.getPath("test_file.txt"); int existingBytesLength = 20; String existingContent = RandomStringUtils.randomAlphanumeric(existingBytesLength); byte[] existingContentBytes = existingContent.getBytes(StandardCharsets.UTF_8); Files.write(testPath, existingContentBytes); int newBytesLength = 10; String newContent = RandomStringUtils.randomAlphanumeric(newBytesLength); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, FileTransformerConfiguration.defaultCreateOrReplaceExisting()); stubSuccessfulStreaming(newContent, transformer); assertThat(testPath).hasContent(newContent); } @Test void createOrAppendExisting_fileDoesNotExist_shouldCreateNewFile() throws Exception { Path testPath = testFs.getPath("test_file.txt"); assertThat(testPath).doesNotExist(); String newContent = RandomStringUtils.randomAlphanumeric(500); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, FileTransformerConfiguration.defaultCreateOrAppend()); stubSuccessfulStreaming(newContent, transformer); assertThat(testPath).hasContent(newContent); } @Test void createOrAppendExisting_fileExists_shouldAppend() throws Exception { Path testPath = testFs.getPath("test_file.txt"); String existingString = RandomStringUtils.randomAlphanumeric(10); byte[] existingBytes = existingString.getBytes(StandardCharsets.UTF_8); Files.write(testPath, existingBytes); String content = RandomStringUtils.randomAlphanumeric(20); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, FileTransformerConfiguration.defaultCreateOrAppend()); stubSuccessfulStreaming(content, transformer); assertThat(testPath).hasContent(existingString + content); } @ParameterizedTest @MethodSource("configurations") void exceptionOccurred_deleteFileBehavior(FileTransformerConfiguration configuration) throws Exception { Path testPath = testFs.getPath("test_file.txt"); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, configuration); stubException(RandomStringUtils.random(200), transformer); if (configuration.failureBehavior() == LEAVE) { assertThat(testPath).exists(); } else { assertThat(testPath).doesNotExist(); } } private static List<FileTransformerConfiguration> configurations() { return Arrays.asList( FileTransformerConfiguration.defaultCreateNew(), FileTransformerConfiguration.defaultCreateOrAppend(), FileTransformerConfiguration.defaultCreateOrReplaceExisting(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_NEW) .failureBehavior(LEAVE).build(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_NEW) .failureBehavior(DELETE).build(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_OR_APPEND_TO_EXISTING) .failureBehavior(DELETE).build(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_OR_APPEND_TO_EXISTING) .failureBehavior(LEAVE).build(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_OR_REPLACE_EXISTING) .failureBehavior(DELETE).build(), FileTransformerConfiguration.builder() .fileWriteOption(FileWriteOption.CREATE_OR_REPLACE_EXISTING) .failureBehavior(LEAVE).build()); } @Test void explicitExecutor_shouldUseExecutor() throws Exception { Path testPath = testFs.getPath("test_file.txt"); assertThat(testPath).doesNotExist(); String newContent = RandomStringUtils.randomAlphanumeric(2000); ExecutorService executor = Executors.newSingleThreadExecutor(); try { SpyingExecutorService spyingExecutorService = new SpyingExecutorService(executor); FileTransformerConfiguration configuration = FileTransformerConfiguration .builder() .fileWriteOption(FileWriteOption.CREATE_NEW) .failureBehavior(DELETE) .executorService(spyingExecutorService) .build(); FileAsyncResponseTransformer<String> transformer = new FileAsyncResponseTransformer<>(testPath, configuration); stubSuccessfulStreaming(newContent, transformer); assertThat(testPath).hasContent(newContent); assertThat(spyingExecutorService.hasReceivedTasks()).isTrue(); } finally { executor.shutdown(); assertThat(executor.awaitTermination(1, TimeUnit.MINUTES)).isTrue(); } } private static void stubSuccessfulStreaming(String newContent, FileAsyncResponseTransformer<String> transformer) throws Exception { CompletableFuture<String> future = transformer.prepare(); transformer.onResponse("foobar"); transformer.onStream(testPublisher(newContent)); future.get(10, TimeUnit.SECONDS); assertThat(future.isCompletedExceptionally()).isFalse(); } private static void stubException(String newContent, FileAsyncResponseTransformer<String> transformer) throws Exception { CompletableFuture<String> future = transformer.prepare(); transformer.onResponse("foobar"); RuntimeException runtimeException = new RuntimeException("oops"); ByteBuffer content = ByteBuffer.wrap(newContent.getBytes(StandardCharsets.UTF_8)); transformer.onStream(SdkPublisher.adapt(Flowable.just(content, content))); transformer.exceptionOccurred(runtimeException); assertThatThrownBy(() -> future.get(10, TimeUnit.SECONDS)) .hasRootCause(runtimeException); assertThat(future.isCompletedExceptionally()).isTrue(); } private static SdkPublisher<ByteBuffer> testPublisher(String content) { return SdkPublisher.adapt(Flowable.just(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)))); } private static final class SpyingExecutorService implements ExecutorService { private final ExecutorService executorService; private boolean receivedTasks = false; private SpyingExecutorService(ExecutorService executorService) { this.executorService = executorService; } public boolean hasReceivedTasks() { return receivedTasks; } @Override public void shutdown() { executorService.shutdown(); } @Override public List<Runnable> shutdownNow() { return executorService.shutdownNow(); } @Override public boolean isShutdown() { return executorService.isShutdown(); } @Override public boolean isTerminated() { return executorService.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return executorService.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { receivedTasks = true; return executorService.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { receivedTasks = true; return executorService.submit(task, result); } @Override public Future<?> submit(Runnable task) { receivedTasks = true; return executorService.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { receivedTasks = true; return executorService.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { receivedTasks = true; return executorService.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { receivedTasks = true; return executorService.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { receivedTasks = true; return executorService.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { receivedTasks = true; executorService.execute(command); } } }
1,663
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/ByteBuffersAsyncRequestBodyTest.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.core.internal.async; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.utils.BinaryUtils; class ByteBuffersAsyncRequestBodyTest { private static class TestSubscriber implements Subscriber<ByteBuffer> { private Subscription subscription; private boolean onCompleteCalled = false; private int callsToComplete = 0; private final List<ByteBuffer> publishedResults = Collections.synchronizedList(new ArrayList<>()); public void request(long n) { subscription.request(n); } @Override public void onSubscribe(Subscription s) { this.subscription = s; } @Override public void onNext(ByteBuffer byteBuffer) { publishedResults.add(byteBuffer); } @Override public void onError(Throwable throwable) { throw new IllegalStateException(throwable); } @Override public void onComplete() { onCompleteCalled = true; callsToComplete++; } } @Test public void subscriberIsMarkedAsCompleted() { AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.from("Hello World!".getBytes(StandardCharsets.UTF_8)); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.request(1); assertTrue(subscriber.onCompleteCalled); assertEquals(1, subscriber.publishedResults.size()); } @Test public void subscriberIsMarkedAsCompletedWhenARequestIsMadeForMoreBuffersThanAreAvailable() { AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.from("Hello World!".getBytes(StandardCharsets.UTF_8)); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.request(2); assertTrue(subscriber.onCompleteCalled); assertEquals(1, subscriber.publishedResults.size()); } @Test public void subscriberIsThreadSafeAndMarkedAsCompletedExactlyOnce() throws InterruptedException { int numBuffers = 100; AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.of(IntStream.range(0, numBuffers) .mapToObj(i -> ByteBuffer.wrap(new byte[1])) .toArray(ByteBuffer[]::new)); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); int parallelism = 8; ExecutorService executorService = Executors.newFixedThreadPool(parallelism); for (int i = 0; i < parallelism; i++) { executorService.submit(() -> { for (int j = 0; j < numBuffers; j++) { subscriber.request(2); } }); } executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); assertTrue(subscriber.onCompleteCalled); assertEquals(1, subscriber.callsToComplete); assertEquals(numBuffers, subscriber.publishedResults.size()); } @Test public void subscriberIsNotMarkedAsCompletedWhenThereAreRemainingBuffersToPublish() { byte[] helloWorld = "Hello World!".getBytes(StandardCharsets.UTF_8); byte[] goodbyeWorld = "Goodbye World!".getBytes(StandardCharsets.UTF_8); AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.of((long) (helloWorld.length + goodbyeWorld.length), ByteBuffer.wrap(helloWorld), ByteBuffer.wrap(goodbyeWorld)); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.request(1); assertFalse(subscriber.onCompleteCalled); assertEquals(1, subscriber.publishedResults.size()); } @Test public void subscriberReceivesAllBuffers() { byte[] helloWorld = "Hello World!".getBytes(StandardCharsets.UTF_8); byte[] goodbyeWorld = "Goodbye World!".getBytes(StandardCharsets.UTF_8); AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.of((long) (helloWorld.length + goodbyeWorld.length), ByteBuffer.wrap(helloWorld), ByteBuffer.wrap(goodbyeWorld)); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.request(2); assertEquals(2, subscriber.publishedResults.size()); assertTrue(subscriber.onCompleteCalled); assertArrayEquals(helloWorld, BinaryUtils.copyAllBytesFrom(subscriber.publishedResults.get(0))); assertArrayEquals(goodbyeWorld, BinaryUtils.copyAllBytesFrom(subscriber.publishedResults.get(1))); } @Test public void multipleSubscribersReceiveTheSameResults() { ByteBuffer sourceBuffer = ByteBuffer.wrap("Hello World!".getBytes(StandardCharsets.UTF_8)); AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.of(sourceBuffer); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.request(1); TestSubscriber otherSubscriber = new TestSubscriber(); requestBody.subscribe(otherSubscriber); otherSubscriber.request(1); ByteBuffer publishedBuffer = subscriber.publishedResults.get(0); ByteBuffer otherPublishedBuffer = otherSubscriber.publishedResults.get(0); assertEquals(publishedBuffer, otherPublishedBuffer); } @Test public void canceledSubscriberDoesNotReturnNewResults() { AsyncRequestBody requestBody = ByteBuffersAsyncRequestBody.of(ByteBuffer.wrap(new byte[0])); TestSubscriber subscriber = new TestSubscriber(); requestBody.subscribe(subscriber); subscriber.subscription.cancel(); subscriber.request(1); assertTrue(subscriber.publishedResults.isEmpty()); } @Test public void staticOfByteBufferConstructorSetsLengthBasedOnBufferRemaining() { ByteBuffer bb1 = ByteBuffer.allocate(2); ByteBuffer bb2 = ByteBuffer.allocate(2); bb2.position(1); ByteBuffersAsyncRequestBody body = ByteBuffersAsyncRequestBody.of(bb1, bb2); assertTrue(body.contentLength().isPresent()); assertEquals(bb1.remaining() + bb2.remaining(), body.contentLength().get()); } @Test public void staticFromBytesConstructorSetsLengthBasedOnArrayLength() { byte[] bytes = new byte[2]; ByteBuffersAsyncRequestBody body = ByteBuffersAsyncRequestBody.from(bytes); assertTrue(body.contentLength().isPresent()); assertEquals(bytes.length, body.contentLength().get()); } }
1,664
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/PublisherAsyncResponseTransformerTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.ByteBuffer; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.ResponsePublisher; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.internal.async.ByteArrayAsyncResponseTransformer.BaosSubscriber; class PublisherAsyncResponseTransformerTest { private PublisherAsyncResponseTransformer<SdkResponse> transformer; private SdkResponse response; private String publisherStr; private SdkPublisher<ByteBuffer> publisher; @BeforeEach public void setUp() throws Exception { transformer = new PublisherAsyncResponseTransformer<>(); response = Mockito.mock(SdkResponse.class); publisherStr = UUID.randomUUID().toString(); publisher = AsyncRequestBody.fromString(publisherStr); } @Test void successfulResponseAndStream_returnsResponsePublisher() throws Exception { CompletableFuture<ResponsePublisher<SdkResponse>> responseFuture = transformer.prepare(); transformer.onResponse(response); assertThat(responseFuture.isDone()).isFalse(); transformer.onStream(publisher); assertThat(responseFuture.isDone()).isTrue(); ResponsePublisher<SdkResponse> responsePublisher = responseFuture.get(); assertThat(responsePublisher.response()).isEqualTo(response); String resultStr = drainPublisherToStr(responsePublisher); assertThat(resultStr).isEqualTo(publisherStr); } @Test void failedResponse_completesExceptionally() { CompletableFuture<ResponsePublisher<SdkResponse>> responseFuture = transformer.prepare(); assertThat(responseFuture.isDone()).isFalse(); transformer.exceptionOccurred(new RuntimeException("Intentional exception for testing purposes")); assertThat(responseFuture.isDone()).isTrue(); assertThatThrownBy(responseFuture::get) .isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(RuntimeException.class); } @Test void failedStream_completesExceptionally() { CompletableFuture<ResponsePublisher<SdkResponse>> responseFuture = transformer.prepare(); transformer.onResponse(response); assertThat(responseFuture.isDone()).isFalse(); transformer.exceptionOccurred(new RuntimeException("Intentional exception for testing purposes")); assertThat(responseFuture.isDone()).isTrue(); assertThatThrownBy(responseFuture::get) .isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(RuntimeException.class); } private static String drainPublisherToStr(SdkPublisher<ByteBuffer> publisher) throws Exception { CompletableFuture<byte[]> bodyFuture = new CompletableFuture<>(); publisher.subscribe(new BaosSubscriber(bodyFuture)); byte[] body = bodyFuture.get(); return new String(body); } }
1,665
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/FileAsyncRequestBodySplitHelperTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.core.internal.async.SplittingPublisherTestUtils.verifyIndividualAsyncRequestBody; import java.io.IOException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.core.async.AsyncRequestBodySplitConfiguration; import software.amazon.awssdk.testutils.RandomTempFile; public class FileAsyncRequestBodySplitHelperTest { private static final int CHUNK_SIZE = 5; private static Path testFile; private static ScheduledExecutorService executor; @BeforeAll public static void setup() throws IOException { testFile = new RandomTempFile(2000).toPath(); executor = Executors.newScheduledThreadPool(1); } @AfterAll public static void teardown() throws IOException { try { Files.delete(testFile); } catch (NoSuchFileException e) { // ignore } executor.shutdown(); } @ParameterizedTest @ValueSource(ints = {CHUNK_SIZE, CHUNK_SIZE * 2 - 1, CHUNK_SIZE * 2}) public void split_differentChunkSize_shouldSplitCorrectly(int chunkSize) throws Exception { long bufferSize = 55l; int chunkSizeInBytes = 10; FileAsyncRequestBody fileAsyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .chunkSizeInBytes(10) .build(); AsyncRequestBodySplitConfiguration config = AsyncRequestBodySplitConfiguration.builder() .chunkSizeInBytes((long) chunkSize) .bufferSizeInBytes(55L) .build(); FileAsyncRequestBodySplitHelper helper = new FileAsyncRequestBodySplitHelper(fileAsyncRequestBody, config); AtomicInteger maxConcurrency = new AtomicInteger(0); ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(verifyConcurrentRequests(helper, maxConcurrency), 1, 50, TimeUnit.MICROSECONDS); verifyIndividualAsyncRequestBody(helper.split(), testFile, chunkSize); scheduledFuture.cancel(true); int expectedMaxConcurrency = (int) (bufferSize / chunkSizeInBytes); assertThat(maxConcurrency.get()).isLessThanOrEqualTo(expectedMaxConcurrency); } private static Runnable verifyConcurrentRequests(FileAsyncRequestBodySplitHelper helper, AtomicInteger maxConcurrency) { return () -> { int concurrency = helper.numAsyncRequestBodiesInFlight().get(); if (concurrency > maxConcurrency.get()) { maxConcurrency.set(concurrency); } assertThat(helper.numAsyncRequestBodiesInFlight()).hasValueLessThan(10); }; } }
1,666
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/BaosSubscriberTckTest.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.core.internal.async; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.internal.async.ByteArrayAsyncResponseTransformer.BaosSubscriber; /** * TCK verification test for {@link BaosSubscriber}. */ public class BaosSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> { private static final byte[] CONTENT = new byte[16]; public BaosSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> whiteboxSubscriberProbe) { return new BaosSubscriber(new CompletableFuture<>()) { @Override public void onSubscribe(Subscription s) { super.onSubscribe(s); whiteboxSubscriberProbe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long l) { s.request(l); } @Override public void signalCancel() { s.cancel(); } }); } @Override public void onNext(ByteBuffer bb) { super.onNext(bb); whiteboxSubscriberProbe.registerOnNext(bb); } @Override public void onError(Throwable t) { super.onError(t); whiteboxSubscriberProbe.registerOnError(t); } @Override public void onComplete() { super.onComplete(); whiteboxSubscriberProbe.registerOnComplete(); } }; } @Override public ByteBuffer createElement(int i) { return ByteBuffer.wrap(CONTENT); } }
1,667
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/ChecksumCalculatingAsyncRequestBodyTest.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.core.internal.async; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import io.reactivex.Flowable; import java.util.stream.Stream; import org.apache.commons.lang3.RandomStringUtils; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.utils.BinaryUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class ChecksumCalculatingAsyncRequestBodyTest { private static final String testString = "Hello world"; private static final String expectedTestString = "b\r\n" + testString + "\r\n" + "0\r\n" + "x-amz-checksum-crc32:i9aeUg==\r\n\r\n"; private static final String emptyString = ""; private static final String expectedEmptyString = "0\r\n" + "x-amz-checksum-crc32:AAAAAA==\r\n\r\n"; private static final Path path; private static final Path pathToEmpty; static { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); path = fs.getPath("./test"); pathToEmpty = fs.getPath("./testEmpty"); try { Files.write(path, testString.getBytes()); Files.write(pathToEmpty, emptyString.getBytes()); } catch (IOException e) { e.printStackTrace(); } } private static Stream<Arguments> publishers() { return Stream.of( Arguments.of("RequestBody from string, test string", checksumPublisher(AsyncRequestBody.fromString(testString)), expectedTestString), Arguments.of("RequestBody from file, test string", checksumPublisher(AsyncRequestBody.fromFile(path)), expectedTestString), Arguments.of("RequestBody from buffer, 0 pos, test string", checksumPublisher(AsyncRequestBody.fromRemainingByteBuffer(posZeroByteBuffer(testString))), expectedTestString), Arguments.of("RequestBody from buffer, random pos, test string", checksumPublisher(AsyncRequestBody.fromRemainingByteBufferUnsafe(nonPosZeroByteBuffer(testString))), expectedTestString), Arguments.of("RequestBody from string, empty string", checksumPublisher(AsyncRequestBody.fromString(emptyString)), expectedEmptyString), //Note: FileAsyncRequestBody with empty file does not call onNext, only onComplete() Arguments.of("RequestBody from file, empty string", checksumPublisher(AsyncRequestBody.fromFile(pathToEmpty)), expectedEmptyString), Arguments.of("RequestBody from buffer, 0 pos, empty string", checksumPublisher(AsyncRequestBody.fromRemainingByteBuffer(posZeroByteBuffer(emptyString))), expectedEmptyString), Arguments.of("RequestBody from string, random pos, empty string", checksumPublisher(AsyncRequestBody.fromRemainingByteBufferUnsafe(nonPosZeroByteBuffer(emptyString))), expectedEmptyString)); } private static ChecksumCalculatingAsyncRequestBody checksumPublisher(AsyncRequestBody sourcePublisher) { return ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(sourcePublisher) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32").build(); } private static ByteBuffer posZeroByteBuffer(String content) { byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); ByteBuffer bytes = ByteBuffer.allocate(contentBytes.length); bytes.put(contentBytes); bytes.flip(); return bytes; } private static ByteBuffer nonPosZeroByteBuffer(String content) { byte[] randomContent = RandomStringUtils.randomAscii(1024).getBytes(StandardCharsets.UTF_8); byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); ByteBuffer bytes = ByteBuffer.allocate(contentBytes.length + randomContent.length); bytes.put(randomContent) .put(contentBytes); bytes.position(randomContent.length); return bytes; } @ParameterizedTest(name = "{index} {0}") @MethodSource("publishers") public void publish_differentAsyncRequestBodiesAndSources_produceCorrectData(String description, AsyncRequestBody provider, String expectedContent) throws InterruptedException { StringBuilder sb = new StringBuilder(); CountDownLatch done = new CountDownLatch(1); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(buffer -> { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); sb.append(new String(bytes, StandardCharsets.UTF_8)); }) { @Override public void onError(Throwable t) { super.onError(t); done.countDown(); } @Override public void onComplete() { super.onComplete(); done.countDown(); } }; provider.subscribe(subscriber); done.await(10, TimeUnit.SECONDS); assertThat(provider.contentLength()).hasValue((long) expectedContent.length()); assertThat(sb).hasToString(expectedContent); } @Test public void constructor_asyncRequestBodyFromString_hasCorrectContentType() { AsyncRequestBody requestBody = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromString("Hello world")) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); assertThat(requestBody.contentType()).startsWith(Mimetype.MIMETYPE_TEXT_PLAIN); } @Test public void constructor_asyncRequestBodyFromFile_hasCorrectContentType() { AsyncRequestBody requestBody = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromFile(path)) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void constructor_asyncRequestBodyFromBytes_hasCorrectContentType() { AsyncRequestBody requestBody = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromBytes("hello world".getBytes())) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void constructor_asyncRequestBodyFromByteBuffer_hasCorrectContentType() { ByteBuffer byteBuffer = ByteBuffer.wrap("hello world".getBytes()); AsyncRequestBody requestBody = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromByteBuffer(byteBuffer)) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void constructor_asyncRequestBodyFromEmpty_hasCorrectContentType() { AsyncRequestBody requestBody = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.empty()) .algorithm(Algorithm.CRC32) .trailerHeader("x-amz-checksum-crc32") .build(); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void constructor_asyncRequestBodyFromPublisher_NoContentLength_throwsException() { List<String> requestBodyStrings = Lists.newArrayList("A", "B", "C"); List<ByteBuffer> bodyBytes = requestBodyStrings.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Publisher<ByteBuffer> bodyPublisher = Flowable.fromIterable(bodyBytes); ChecksumCalculatingAsyncRequestBody.Builder builder = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromPublisher(bodyPublisher)) .algorithm(Algorithm.SHA1) .trailerHeader("x-amz-checksum-sha1"); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> builder.build()); } @Test public void constructor_checksumIsNull_throwsException() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromString("Hello world")) .trailerHeader("x-amzn-checksum-crc32") .build()).withMessage("algorithm cannot be null"); } @Test public void constructor_asyncRequestBodyIsNull_throwsException() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> ChecksumCalculatingAsyncRequestBody.builder() .algorithm(Algorithm.CRC32) .trailerHeader("x-amzn-checksum-crc32") .build()).withMessage("wrapped AsyncRequestBody cannot be null"); } @Test public void constructor_trailerHeaderIsNull_throwsException() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> ChecksumCalculatingAsyncRequestBody.builder() .algorithm(Algorithm.CRC32) .asyncRequestBody(AsyncRequestBody.fromString("Hello world")) .build()).withMessage("trailerHeader cannot be null"); } @Test public void fromBytes_byteArrayNotNullChecksumSupplied() { byte[] original = {1, 2, 3, 4}; // Checksum data in byte format. byte[] expected = {52, 13, 10, 1, 2, 3, 4, 13, 10, 48, 13, 10, 120, 45, 97, 109, 122, 110, 45, 99, 104, 101, 99, 107, 115, 117, 109, 45, 99, 114, 99, 51, 50, 58, 116, 106, 122, 55, 122, 81, 61, 61, 13, 10, 13, 10}; byte[] toModify = new byte[original.length]; System.arraycopy(original, 0, toModify, 0, original.length); AsyncRequestBody body = ChecksumCalculatingAsyncRequestBody.builder() .asyncRequestBody(AsyncRequestBody.fromBytes(toModify)) .algorithm(Algorithm.CRC32) .trailerHeader("x-amzn-checksum-crc32") .build(); for (int i = 0; i < toModify.length; ++i) { toModify[i]++; } ByteBuffer publishedBb = Flowable.fromPublisher(body).toList().blockingGet().get(0); assertThat(BinaryUtils.copyAllBytesFrom(publishedBb)).isEqualTo(expected); } }
1,668
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/CompressionAsyncRequestBodyTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.http.async.SimpleSubscriber; public final class CompressionAsyncRequestBodyTest { private static final Compressor compressor = new GzipCompressor(); @ParameterizedTest @ValueSource(ints = {80, 1000}) public void hasCorrectContent(int bodySize) throws Exception { String testString = createCompressibleStringOfGivenSize(bodySize); byte[] testBytes = testString.getBytes(); int chunkSize = 133; AsyncRequestBody provider = CompressionAsyncRequestBody.builder() .compressor(compressor) .asyncRequestBody(customAsyncRequestBodyWithoutContentLength(testBytes)) .chunkSize(chunkSize) .build(); ByteBuffer byteBuffer = ByteBuffer.allocate(testString.length()); CountDownLatch done = new CountDownLatch(1); AtomicInteger pos = new AtomicInteger(); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(buffer -> { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); byteBuffer.put(bytes); // verify each chunk byte[] chunkToVerify = new byte[chunkSize]; System.arraycopy(testBytes, pos.get(), chunkToVerify, 0, chunkSize); chunkToVerify = compressor.compress(chunkToVerify); assertThat(bytes).isEqualTo(chunkToVerify); pos.addAndGet(chunkSize); }) { @Override public void onError(Throwable t) { super.onError(t); done.countDown(); } @Override public void onComplete() { super.onComplete(); done.countDown(); } }; provider.subscribe(subscriber); done.await(10, TimeUnit.SECONDS); byte[] retrieved = byteBuffer.array(); byte[] uncompressed = decompress(retrieved); assertThat(new String(uncompressed)).isEqualTo(testString); } @Test public void emptyBytesConstructor_hasEmptyContent() throws Exception { AsyncRequestBody requestBody = CompressionAsyncRequestBody.builder() .compressor(compressor) .asyncRequestBody(AsyncRequestBody.empty()) .build(); ByteBuffer byteBuffer = ByteBuffer.allocate(0); CountDownLatch done = new CountDownLatch(1); Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(buffer -> { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); byteBuffer.put(bytes); }) { @Override public void onError(Throwable t) { super.onError(t); done.countDown(); } @Override public void onComplete() { super.onComplete(); done.countDown(); } }; requestBody.subscribe(subscriber); done.await(10, TimeUnit.SECONDS); assertThat(byteBuffer.array()).isEmpty(); assertThat(byteBuffer.array()).isEqualTo(new byte[0]); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } private static String createCompressibleStringOfGivenSize(int size) { ByteBuffer data = ByteBuffer.allocate(size); byte[] a = new byte[size / 4]; byte[] b = new byte[size / 4]; Arrays.fill(a, (byte) 'a'); Arrays.fill(b, (byte) 'b'); data.put(a); data.put(b); data.put(a); data.put(b); return new String(data.array()); } private static byte[] decompress(byte[] compressedData) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(compressedData); GZIPInputStream gzipInputStream = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = gzipInputStream.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } gzipInputStream.close(); byte[] decompressedData = baos.toByteArray(); return decompressedData; } private static AsyncRequestBody customAsyncRequestBodyWithoutContentLength(byte[] content) { return new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Flowable.fromPublisher(AsyncRequestBody.fromBytes(content)) .subscribe(s); } }; } }
1,669
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/InputStreamResponseTransformerTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.utils.async.SimplePublisher; class InputStreamResponseTransformerTest { private SimplePublisher<ByteBuffer> publisher; private InputStreamResponseTransformer<SdkResponse> transformer; private SdkResponse response; private CompletableFuture<ResponseInputStream<SdkResponse>> resultFuture; @BeforeEach public void setup() { publisher = new SimplePublisher<>(); transformer = new InputStreamResponseTransformer<>(); resultFuture = transformer.prepare(); response = VoidSdkResponse.builder().build(); transformer.onResponse(response); assertThat(resultFuture).isNotDone(); transformer.onStream(SdkPublisher.adapt(publisher)); assertThat(resultFuture).isCompleted(); assertThat(resultFuture.join().response()).isEqualTo(response); } @Test public void inputStreamReadsAreFromPublisher() throws IOException { InputStream stream = resultFuture.join(); publisher.send(ByteBuffer.wrap(new byte[] { 0, 1, 2 })); publisher.complete(); assertThat(stream.read()).isEqualTo(0); assertThat(stream.read()).isEqualTo(1); assertThat(stream.read()).isEqualTo(2); assertThat(stream.read()).isEqualTo(-1); } @Test public void inputStreamArrayReadsAreFromPublisher() throws IOException { InputStream stream = resultFuture.join(); publisher.send(ByteBuffer.wrap(new byte[] { 0, 1, 2 })); publisher.complete(); byte[] data = new byte[3]; assertThat(stream.read(data)).isEqualTo(3); assertThat(data[0]).isEqualTo((byte) 0); assertThat(data[1]).isEqualTo((byte) 1); assertThat(data[2]).isEqualTo((byte) 2); assertThat(stream.read(data)).isEqualTo(-1); } }
1,670
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/InputStreamWithExecutorAsyncRequestBodyTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult; class InputStreamWithExecutorAsyncRequestBodyTest { @Test @Timeout(10) public void dataFromInputStreamIsCopied() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); try { PipedOutputStream os = new PipedOutputStream(); PipedInputStream is = new PipedInputStream(os); InputStreamWithExecutorAsyncRequestBody asyncRequestBody = (InputStreamWithExecutorAsyncRequestBody) AsyncRequestBody.fromInputStream(b -> b.inputStream(is).executor(executor).contentLength(4L)); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(8); asyncRequestBody.subscribe(subscriber); os.write(0); os.write(1); os.write(2); os.write(3); os.close(); asyncRequestBody.activeWriteFuture().get(); ByteBuffer output = ByteBuffer.allocate(8); assertThat(subscriber.transferTo(output)).isEqualTo(TransferResult.END_OF_STREAM); output.flip(); assertThat(output.remaining()).isEqualTo(4); assertThat(output.get()).isEqualTo((byte) 0); assertThat(output.get()).isEqualTo((byte) 1); assertThat(output.get()).isEqualTo((byte) 2); assertThat(output.get()).isEqualTo((byte) 3); } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void errorsReadingInputStreamAreForwardedToSubscriber() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); try { PipedOutputStream os = new PipedOutputStream(); PipedInputStream is = new PipedInputStream(os); is.close(); InputStreamWithExecutorAsyncRequestBody asyncRequestBody = (InputStreamWithExecutorAsyncRequestBody) AsyncRequestBody.fromInputStream(b -> b.inputStream(is).executor(executor).contentLength(4L)); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(8); asyncRequestBody.subscribe(subscriber); assertThatThrownBy(() -> asyncRequestBody.activeWriteFuture().get()).hasRootCauseInstanceOf(IOException.class); assertThatThrownBy(() -> subscriber.transferTo(ByteBuffer.allocate(8))).hasRootCauseInstanceOf(IOException.class); } finally { executor.shutdownNow(); } } }
1,671
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/AsyncStreamPrependerTest.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.core.internal.async; import io.reactivex.Flowable; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.testng.Assert; import java.util.Iterator; import java.util.List; import static io.reactivex.Flowable.fromPublisher; import static io.reactivex.Flowable.just; import static io.reactivex.Flowable.rangeLong; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.testng.Assert.assertThrows; public class AsyncStreamPrependerTest { @Test public void empty() { Flowable<Long> prepender = fromPublisher(new AsyncStreamPrepender<>(Flowable.empty(), 0L)); List<Long> actual = prepender.toList().blockingGet(); assertEquals(singletonList(0L), actual); } @Test public void single() { Flowable<Long> prepender = fromPublisher(new AsyncStreamPrepender<>(just(1L), 0L)); List<Long> actual = prepender.toList().blockingGet(); assertEquals(asList(0L, 1L), actual); } @Test public void sequence() { Flowable<Long> prepender = fromPublisher(new AsyncStreamPrepender<>(rangeLong(1L, 5L), 0L)); Iterator<Long> iterator = prepender.blockingIterable(1).iterator(); for (long i = 0; i <= 5; i++) { assertEquals(i, iterator.next().longValue()); } } @Test public void multiSubscribe_stillPrepends() { AsyncStreamPrepender<Long> prepender = new AsyncStreamPrepender<>(rangeLong(1L, 5L), 0L); Flowable<Long> prepended1 = fromPublisher(prepender); Flowable<Long> prepended2 = fromPublisher(prepender); Iterator<Long> iterator1 = prepended1.blockingIterable(1).iterator(); Iterator<Long> iterator2 = prepended2.blockingIterable(1).iterator(); for (long i = 0; i <= 5; i++) { assertEquals(i, iterator1.next().longValue()); assertEquals(i, iterator2.next().longValue()); } } @Test public void error() { Flowable<Long> error = Flowable.error(IllegalStateException::new); Flowable<Long> prepender = fromPublisher(new AsyncStreamPrepender<>(error, 0L)); Iterator<Long> iterator = prepender.blockingNext().iterator(); assertThrows(IllegalStateException.class, iterator::next); } @Test(expected = IllegalArgumentException.class) public void negativeRequest() { Flowable<Long> prepender = fromPublisher(new AsyncStreamPrepender<>(rangeLong(1L, 5L), 0L)); prepender.blockingSubscribe(new Subscriber<Long>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(-1L); } @Override public void onError(Throwable throwable) { if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } } @Override public void onNext(Long aLong) {} @Override public void onComplete() {} }); } }
1,672
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/AyncStreamPrependerTckTest.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.core.internal.async; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import io.reactivex.Flowable; public class AyncStreamPrependerTckTest extends PublisherVerification<Long> { public AyncStreamPrependerTckTest() { super(new TestEnvironment()); } @Override public Publisher<Long> createPublisher(long l) { if (l == 0) { return Flowable.empty(); } else { Flowable<Long> delegate = Flowable.rangeLong(1, l - 1); return new AsyncStreamPrepender<>(delegate, 0L); } } @Override public Publisher<Long> createFailedPublisher() { return new AsyncStreamPrepender<>(Flowable.error(new NullPointerException()), 0L); } }
1,673
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/SplittingPublisherTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.core.internal.async.SplittingPublisherTestUtils.verifyIndividualAsyncRequestBody; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncRequestBodySplitConfiguration; import software.amazon.awssdk.utils.BinaryUtils; public class SplittingPublisherTest { private static final int CHUNK_SIZE = 5; private static final int CONTENT_SIZE = 101; private static final byte[] CONTENT = RandomStringUtils.randomAscii(CONTENT_SIZE).getBytes(Charset.defaultCharset()); private static final int NUM_OF_CHUNK = (int) Math.ceil(CONTENT_SIZE / (double) CHUNK_SIZE); private static File testFile; @BeforeAll public static void beforeAll() throws IOException { testFile = File.createTempFile("SplittingPublisherTest", UUID.randomUUID().toString()); Files.write(testFile.toPath(), CONTENT); } @AfterAll public static void afterAll() throws Exception { testFile.delete(); } @Test public void split_contentUnknownMaxMemorySmallerThanChunkSize_shouldThrowException() { AsyncRequestBody body = AsyncRequestBody.fromPublisher(s -> { }); assertThatThrownBy(() -> new SplittingPublisher(body, AsyncRequestBodySplitConfiguration.builder() .chunkSizeInBytes(10L) .bufferSizeInBytes(5L) .build())) .hasMessageContaining("must be larger than or equal"); } @ParameterizedTest @ValueSource(ints = {CHUNK_SIZE, CHUNK_SIZE * 2 - 1, CHUNK_SIZE * 2}) void differentChunkSize_shouldSplitAsyncRequestBodyCorrectly(int chunkSize) throws Exception { FileAsyncRequestBody fileAsyncRequestBody = FileAsyncRequestBody.builder() .path(testFile.toPath()) .chunkSizeInBytes(chunkSize) .build(); verifySplitContent(fileAsyncRequestBody, chunkSize); } @ParameterizedTest @ValueSource(ints = {CHUNK_SIZE, CHUNK_SIZE * 2 - 1, CHUNK_SIZE * 2}) void differentChunkSize_byteArrayShouldSplitAsyncRequestBodyCorrectly(int chunkSize) throws Exception { verifySplitContent(AsyncRequestBody.fromBytes(CONTENT), chunkSize); } @Test void contentLengthNotPresent_shouldHandle() throws Exception { CompletableFuture<Void> future = new CompletableFuture<>(); TestAsyncRequestBody asyncRequestBody = new TestAsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } }; SplittingPublisher splittingPublisher = new SplittingPublisher(asyncRequestBody, AsyncRequestBodySplitConfiguration.builder() .chunkSizeInBytes((long) CHUNK_SIZE) .bufferSizeInBytes(10L) .build()); List<CompletableFuture<byte[]>> futures = new ArrayList<>(); AtomicInteger index = new AtomicInteger(0); splittingPublisher.subscribe(requestBody -> { CompletableFuture<byte[]> baosFuture = new CompletableFuture<>(); BaosSubscriber subscriber = new BaosSubscriber(baosFuture); futures.add(baosFuture); requestBody.subscribe(subscriber); if (index.incrementAndGet() == NUM_OF_CHUNK) { assertThat(requestBody.contentLength()).hasValue(1L); } else { assertThat(requestBody.contentLength()).hasValue((long) CHUNK_SIZE); } }).get(5, TimeUnit.SECONDS); assertThat(futures.size()).isEqualTo(NUM_OF_CHUNK); for (int i = 0; i < futures.size(); i++) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(CONTENT)) { byte[] expected; if (i == futures.size() - 1) { expected = new byte[1]; } else { expected = new byte[CHUNK_SIZE]; } inputStream.skip(i * CHUNK_SIZE); inputStream.read(expected); byte[] actualBytes = futures.get(i).join(); assertThat(actualBytes).isEqualTo(expected); }; } } private static void verifySplitContent(AsyncRequestBody asyncRequestBody, int chunkSize) throws Exception { SplittingPublisher splittingPublisher = new SplittingPublisher(asyncRequestBody, AsyncRequestBodySplitConfiguration.builder() .chunkSizeInBytes((long) chunkSize) .bufferSizeInBytes((long) chunkSize * 4) .build()); verifyIndividualAsyncRequestBody(splittingPublisher, testFile.toPath(), chunkSize); } private static class TestAsyncRequestBody implements AsyncRequestBody { private volatile boolean cancelled; private volatile boolean isDone; @Override public Optional<Long> contentLength() { return Optional.of((long) CONTENT.length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { if (isDone) { return; } isDone = true; s.onNext(ByteBuffer.wrap(CONTENT)); s.onComplete(); } @Override public void cancel() { cancelled = true; } }); } } private static final class OnlyRequestOnceSubscriber implements Subscriber<AsyncRequestBody> { private List<AsyncRequestBody> asyncRequestBodies = new ArrayList<>(); @Override public void onSubscribe(Subscription s) { s.request(1); } @Override public void onNext(AsyncRequestBody requestBody) { asyncRequestBodies.add(requestBody); } @Override public void onError(Throwable t) { } @Override public void onComplete() { } } private static final class BaosSubscriber implements Subscriber<ByteBuffer> { private final CompletableFuture<byte[]> resultFuture; private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private Subscription subscription; BaosSubscriber(CompletableFuture<byte[]> resultFuture) { this.resultFuture = resultFuture; } @Override public void onSubscribe(Subscription s) { if (this.subscription != null) { s.cancel(); return; } this.subscription = s; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { invokeSafely(() -> baos.write(BinaryUtils.copyBytesFrom(byteBuffer))); subscription.request(1); } @Override public void onError(Throwable throwable) { baos = null; resultFuture.completeExceptionally(throwable); } @Override public void onComplete() { resultFuture.complete(baos.toByteArray()); } } }
1,674
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/FileAsyncRequestBodyTest.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.core.internal.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertTrue; import static software.amazon.awssdk.core.internal.async.SplittingPublisherTestUtils.verifyIndividualAsyncRequestBody; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.utils.BinaryUtils; public class FileAsyncRequestBodyTest { private static final long MiB = 1024 * 1024; private static final long TEST_FILE_SIZE = 10 * MiB; private static Path testFile; private static Path smallFile; @BeforeEach public void setup() throws IOException { testFile = new RandomTempFile(TEST_FILE_SIZE).toPath(); smallFile = new RandomTempFile(100).toPath(); } @AfterEach public void teardown() throws IOException { try { Files.delete(testFile); } catch (NoSuchFileException e) { // ignore } } // If we issue just enough requests to read the file entirely but not more (to go past EOF), we should still receive // an onComplete @Test public void readFully_doesNotRequestPastEndOfFile_receivesComplete() throws Exception { int chunkSize = 16384; AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .chunkSizeInBytes(chunkSize) .build(); long totalRequests = TEST_FILE_SIZE / chunkSize; CompletableFuture<Void> completed = new CompletableFuture<>(); asyncRequestBody.subscribe(new Subscriber<ByteBuffer>() { private Subscription sub; private long requests = 0; @Override public void onSubscribe(Subscription subscription) { this.sub = subscription; if (requests++ < totalRequests) { this.sub.request(1); } } @Override public void onNext(ByteBuffer byteBuffer) { if (requests++ < totalRequests) { this.sub.request(1); } } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { completed.complete(null); } }); completed.get(5, TimeUnit.SECONDS); } @Test public void changingFile_fileGetsShorterThanAlreadyRead_failsBecauseTooShort() throws Exception { AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .build(); ControllableSubscriber subscriber = new ControllableSubscriber(); // Start reading file asyncRequestBody.subscribe(subscriber); subscriber.sub.request(1); assertTrue(subscriber.onNextSemaphore.tryAcquire(5, TimeUnit.SECONDS)); // Change the file to be shorter than the amount read so far Files.write(testFile, "Hello".getBytes(StandardCharsets.UTF_8)); // Finishing reading the file subscriber.sub.request(Long.MAX_VALUE); assertThatThrownBy(() -> subscriber.completed.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IOException.class); } @Test public void changingFile_fileGetsShorterThanExistingLength_failsBecauseTooShort() throws Exception { AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .build(); ControllableSubscriber subscriber = new ControllableSubscriber(); // Start reading file asyncRequestBody.subscribe(subscriber); subscriber.sub.request(1); assertTrue(subscriber.onNextSemaphore.tryAcquire(5, TimeUnit.SECONDS)); // Change the file to be 1 byte shorter than when we started int currentSize = Math.toIntExact(Files.size(testFile)); byte[] slightlyShorterFileContent = new byte[currentSize - 1]; ThreadLocalRandom.current().nextBytes(slightlyShorterFileContent); Files.write(testFile, slightlyShorterFileContent); // Finishing reading the file subscriber.sub.request(Long.MAX_VALUE); assertThatThrownBy(() -> subscriber.completed.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IOException.class); } @Test public void changingFile_fileGetsLongerThanExistingLength_failsBecauseTooLong() throws Exception { AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .build(); ControllableSubscriber subscriber = new ControllableSubscriber(); // Start reading file asyncRequestBody.subscribe(subscriber); subscriber.sub.request(1); assertTrue(subscriber.onNextSemaphore.tryAcquire(5, TimeUnit.SECONDS)); // Change the file to be 1 byte longer than when we started int currentSize = Math.toIntExact(Files.size(testFile)); byte[] slightlyLongerFileContent = new byte[currentSize + 1]; ThreadLocalRandom.current().nextBytes(slightlyLongerFileContent); Files.write(testFile, slightlyLongerFileContent); // Finishing reading the file subscriber.sub.request(Long.MAX_VALUE); assertThatThrownBy(() -> subscriber.completed.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IOException.class); } @Test public void changingFile_fileGetsTouched_failsBecauseUpdatedModificationTime() throws Exception { AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .build(); ControllableSubscriber subscriber = new ControllableSubscriber(); // Start reading file asyncRequestBody.subscribe(subscriber); subscriber.sub.request(1); assertTrue(subscriber.onNextSemaphore.tryAcquire(5, TimeUnit.SECONDS)); // Change the file to be updated Thread.sleep(1_000); // Wait for 1 second so that we are definitely in a different second than when the file was created Files.setLastModifiedTime(testFile, FileTime.from(Instant.now())); // Finishing reading the file subscriber.sub.request(Long.MAX_VALUE); assertThatThrownBy(() -> subscriber.completed.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IOException.class); } @Test public void changingFile_fileGetsDeleted_failsBecauseDeleted() throws Exception { AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(testFile) .build(); ControllableSubscriber subscriber = new ControllableSubscriber(); // Start reading file asyncRequestBody.subscribe(subscriber); subscriber.sub.request(1); assertTrue(subscriber.onNextSemaphore.tryAcquire(5, TimeUnit.SECONDS)); // Delete the file Files.delete(testFile); // Finishing reading the file subscriber.sub.request(Long.MAX_VALUE); assertThatThrownBy(() -> subscriber.completed.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IOException.class); } @Test public void positionNotZero_shouldReadFromPosition() throws Exception { CompletableFuture<byte[]> future = new CompletableFuture<>(); long position = 20L; AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(smallFile) .position(position) .chunkSizeInBytes(10) .build(); ByteArrayAsyncResponseTransformer.BaosSubscriber baosSubscriber = new ByteArrayAsyncResponseTransformer.BaosSubscriber(future); asyncRequestBody.subscribe(baosSubscriber); assertThat(asyncRequestBody.contentLength()).contains(80L); byte[] bytes = future.get(1, TimeUnit.SECONDS); byte[] expected = new byte[80]; try(FileInputStream inputStream = new FileInputStream(smallFile.toFile())) { inputStream.skip(position); inputStream.read(expected, 0, 80); } assertThat(bytes).isEqualTo(expected); } @Test public void bothPositionAndNumBytesToReadConfigured_shouldHonor() throws Exception { CompletableFuture<byte[]> future = new CompletableFuture<>(); long position = 20L; long numBytesToRead = 5L; AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(smallFile) .position(position) .numBytesToRead(numBytesToRead) .chunkSizeInBytes(10) .build(); ByteArrayAsyncResponseTransformer.BaosSubscriber baosSubscriber = new ByteArrayAsyncResponseTransformer.BaosSubscriber(future); asyncRequestBody.subscribe(baosSubscriber); assertThat(asyncRequestBody.contentLength()).contains(numBytesToRead); byte[] bytes = future.get(1, TimeUnit.SECONDS); byte[] expected = new byte[5]; try (FileInputStream inputStream = new FileInputStream(smallFile.toFile())) { inputStream.skip(position); inputStream.read(expected, 0, 5); } assertThat(bytes).isEqualTo(expected); } @Test public void numBytesToReadConfigured_shouldHonor() throws Exception { CompletableFuture<byte[]> future = new CompletableFuture<>(); AsyncRequestBody asyncRequestBody = FileAsyncRequestBody.builder() .path(smallFile) .numBytesToRead(5L) .chunkSizeInBytes(10) .build(); ByteArrayAsyncResponseTransformer.BaosSubscriber baosSubscriber = new ByteArrayAsyncResponseTransformer.BaosSubscriber(future); asyncRequestBody.subscribe(baosSubscriber); assertThat(asyncRequestBody.contentLength()).contains(5L); byte[] bytes = future.get(1, TimeUnit.SECONDS); byte[] expected = new byte[5]; try (FileInputStream inputStream = new FileInputStream(smallFile.toFile())) { inputStream.read(expected, 0, 5); } assertThat(bytes).isEqualTo(expected); } private static class ControllableSubscriber implements Subscriber<ByteBuffer> { private final ByteArrayOutputStream output = new ByteArrayOutputStream(); private final CompletableFuture<Void> completed = new CompletableFuture<>(); private final Semaphore onNextSemaphore = new Semaphore(0); private Subscription sub; @Override public void onSubscribe(Subscription subscription) { this.sub = subscription; } @Override public void onNext(ByteBuffer byteBuffer) { invokeSafely(() -> output.write(BinaryUtils.copyBytesFrom(byteBuffer))); onNextSemaphore.release(); } @Override public void onError(Throwable throwable) { completed.completeExceptionally(throwable); } @Override public void onComplete() { completed.complete(null); } } }
1,675
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/async/FileSubscriberTckTest.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.core.internal.async; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.internal.async.FileAsyncResponseTransformer.FileSubscriber; /** * TCK verification test for {@link FileSubscriber}. */ public class FileSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> { private static final byte[] CONTENT = new byte[16]; private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); public FileSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> whiteboxSubscriberProbe) { Path tempFile = getNewTempFile(); return new FileSubscriber(openChannel(tempFile), tempFile, new CompletableFuture<>(), (t) -> {}, 0) { @Override public void onSubscribe(Subscription s) { super.onSubscribe(s); whiteboxSubscriberProbe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long l) { s.request(l); } @Override public void signalCancel() { s.cancel(); } }); } @Override public void onNext(ByteBuffer bb) { super.onNext(bb); whiteboxSubscriberProbe.registerOnNext(bb); } @Override public void onError(Throwable t) { super.onError(t); whiteboxSubscriberProbe.registerOnError(t); } @Override public void onComplete() { super.onComplete(); whiteboxSubscriberProbe.registerOnComplete(); } }; } @Override public ByteBuffer createElement(int i) { return ByteBuffer.wrap(CONTENT); } private Path getNewTempFile() { return fs.getPath("/", UUID.randomUUID().toString()); } private AsynchronousFileChannel openChannel(Path p) { try { return AsynchronousFileChannel.open(p, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); } catch (IOException e) { throw new UncheckedIOException(e); } } }
1,676
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/io/BufferedInputStreamResetTest.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.core.internal.io; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.jupiter.api.Test; /** * This test demonstrates why we should call mark(Integer.MAX_VALUE) instead of * mark(-1). */ public class BufferedInputStreamResetTest { @Test public void testNeatives() throws IOException { testNegative(-1); // fixed buffer testNegative(19); // 1 byte short } private void testNegative(final int readLimit) throws IOException { byte[] bytes = new byte[100]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) i; } // buffer of 10 bytes BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes), 10); // skip 10 bytes bis.skip(10); bis.mark(readLimit); // 1 byte short in buffer size // read 30 bytes in total, with internal buffer incread to 20 bis.read(new byte[20]); try { bis.reset(); fail(); } catch (IOException ex) { assertEquals("Resetting to invalid mark", ex.getMessage()); } } @Test public void testPositives() throws IOException { testPositive(20); // just enough testPositive(Integer.MAX_VALUE); } private void testPositive(final int readLimit) throws IOException { byte[] bytes = new byte[100]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) i; } // buffer of 10 bytes BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes), 10); // skip 10 bytes bis.skip(10); bis.mark(readLimit); // buffer size would increase up to readLimit // read 30 bytes in total, with internal buffer increased to 20 bis.read(new byte[20]); bis.reset(); assert (bis.read() == 10); } }
1,677
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/io/SdkLengthAwareInputStreamTest.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.core.internal.io; 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.when; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SdkLengthAwareInputStreamTest { private InputStream delegateStream; @BeforeEach void setup() { delegateStream = mock(InputStream.class); } @Test void read_lengthIs0_returnsEof() throws IOException { when(delegateStream.available()).thenReturn(Integer.MAX_VALUE); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 0); assertThat(is.read()).isEqualTo(-1); assertThat(is.read(new byte[16], 0, 16)).isEqualTo(-1); } @Test void read_lengthNonZero_delegateEof_returnsEof() throws IOException { when(delegateStream.read()).thenReturn(-1); when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenReturn(-1); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 0); assertThat(is.read()).isEqualTo(-1); assertThat(is.read(new byte[16], 0, 16)).isEqualTo(-1); } @Test void readByte_lengthNonZero_delegateHasAvailable_returnsDelegateData() throws IOException { when(delegateStream.read()).thenReturn(42); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); assertThat(is.read()).isEqualTo(42); } @Test void readArray_lengthNonZero_delegateHasAvailable_returnsDelegateData() throws IOException { when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenReturn(8); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); assertThat(is.read(new byte[16], 0, 16)).isEqualTo(8); } @Test void readArray_lengthNonZero_propagatesCallToDelegate() throws IOException { when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenReturn(8); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); byte[] buff = new byte[16]; is.read(buff, 0, 16); verify(delegateStream).read(buff, 0, 16); } @Test void read_markAndReset_availableReflectsNewLength() throws IOException { delegateStream = new ByteArrayInputStream(new byte[32]); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); for (int i = 0; i < 4; ++i) { is.read(); } assertThat(is.available()).isEqualTo(12); is.mark(16); for (int i = 0; i < 4; ++i) { is.read(); } assertThat(is.available()).isEqualTo(8); is.reset(); assertThat(is.available()).isEqualTo(12); } @Test void skip_markAndReset_availableReflectsNewLength() throws IOException { delegateStream = new ByteArrayInputStream(new byte[32]); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); is.skip(4); assertThat(is.remaining()).isEqualTo(12); is.mark(16); for (int i = 0; i < 4; ++i) { is.read(); } assertThat(is.remaining()).isEqualTo(8); is.reset(); assertThat(is.remaining()).isEqualTo(12); } @Test void skip_delegateSkipsLessThanRequested_availableUpdatedCorrectly() throws IOException { when(delegateStream.skip(any(long.class))).thenAnswer(i -> { Long n = i.getArgument(0, Long.class); return n / 2; }); when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenReturn(1); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); long skipped = is.skip(4); assertThat(skipped).isEqualTo(2); assertThat(is.remaining()).isEqualTo(14); } @Test void readArray_delegateReadsLessThanRequested_availableUpdatedCorrectly() throws IOException { when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenAnswer(i -> { Integer n = i.getArgument(2, Integer.class); return n / 2; }); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); long read = is.read(new byte[16], 0, 8); assertThat(read).isEqualTo(4); assertThat(is.remaining()).isEqualTo(12); } @Test void read_delegateAtEof_returnsEof() throws IOException { when(delegateStream.read()).thenReturn(-1); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); assertThat(is.read()).isEqualTo(-1); } @Test void readArray_delegateAtEof_returnsEof() throws IOException { when(delegateStream.read(any(byte[].class), any(int.class), any(int.class))).thenReturn(-1); SdkLengthAwareInputStream is = new SdkLengthAwareInputStream(delegateStream, 16); assertThat(is.read(new byte[8], 0, 8)).isEqualTo(-1); } }
1,678
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/io/AwsCompressionInputStreamTest.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.core.internal.io; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.core.util.FileUtils.generateRandomAsciiFile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; public class AwsCompressionInputStreamTest { private static Compressor compressor; @BeforeClass public static void setup() throws IOException { compressor = new GzipCompressor(); } @Test public void nonMarkSupportedInputStream_marksAndResetsCorrectly() throws IOException { File file = generateRandomAsciiFile(100); InputStream is = new FileInputStream(file); assertFalse(is.markSupported()); AwsCompressionInputStream compressionInputStream = AwsCompressionInputStream.builder() .inputStream(is) .compressor(compressor) .build(); compressionInputStream.mark(100); compressionInputStream.reset(); String read1 = readInputStream(compressionInputStream); compressionInputStream.reset(); String read2 = readInputStream(compressionInputStream); assertThat(read1).isEqualTo(read2); } @Test public void markSupportedInputStream_marksAndResetsCorrectly() throws IOException { InputStream is = new ByteArrayInputStream(generateRandomBody(100)); assertTrue(is.markSupported()); AwsCompressionInputStream compressionInputStream = AwsCompressionInputStream.builder() .inputStream(is) .compressor(compressor) .build(); compressionInputStream.mark(100); compressionInputStream.reset(); String read1 = readInputStream(compressionInputStream); compressionInputStream.reset(); String read2 = readInputStream(compressionInputStream); assertThat(read1).isEqualTo(read2); } private byte[] generateRandomBody(int size) { byte[] randomData = new byte[size]; new Random().nextBytes(randomData); return randomData; } private String readInputStream(InputStream is) throws IOException { byte[] buffer = new byte[512]; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } return byteArrayOutputStream.toString(); } }
1,679
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/io/ResettableInputStreamTest.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.core.internal.io; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.core.util.FileUtils.generateRandomAsciiFile; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.ClosedChannelException; import java.util.Optional; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.io.ReleasableInputStream; import software.amazon.awssdk.core.io.ResettableInputStream; public class ResettableInputStreamTest { private static File file; @BeforeClass public static void setup() throws IOException { file = generateRandomAsciiFile(100); } @Test public void testFileInputStream() throws IOException { try (InputStream is = new FileInputStream(file)) { assertFalse(is.markSupported()); String content = IOUtils.toString(is); String content2 = IOUtils.toString(is); assertTrue(content.length() == 100); assertEquals(content2, ""); } } @Test public void testResetInputStreamWithFile() throws IOException { try (ResettableInputStream is = new ResettableInputStream(file)) { assertTrue(is.markSupported()); String content = IOUtils.toString(is); is.reset(); String content2 = IOUtils.toString(is); assertTrue(content.length() == 100); assertEquals(content, content2); assertEquals(file, is.getFile()); } } @Test public void testResetFileInputStream() throws IOException { try (ResettableInputStream is = new ResettableInputStream( new FileInputStream(file))) { assertTrue(is.markSupported()); String content = IOUtils.toString(is); is.reset(); String content2 = IOUtils.toString(is); assertTrue(content.length() == 100); assertEquals(content, content2); assertNull(is.getFile()); } } @Test public void testMarkAndResetWithFile() throws IOException { try (ResettableInputStream is = new ResettableInputStream(file)) { is.read(new byte[10]); is.mark(-1); String content = IOUtils.toString(is); is.reset(); String content2 = IOUtils.toString(is); assertTrue(content.length() == 90); assertEquals(content, content2); } } @Test public void testMarkAndResetFileInputStream() throws IOException { try (ResettableInputStream is = new ResettableInputStream(new FileInputStream(file))) { is.read(new byte[10]); is.mark(-1); String content = IOUtils.toString(is); is.reset(); String content2 = IOUtils.toString(is); assertTrue(content.length() == 90); assertEquals(content, content2); } } @Test public void testResetWithClosedFile() throws IOException { ResettableInputStream is = null; try { is = new ResettableInputStream(file).disableClose(); String content = IOUtils.toString(is); is.close(); is.reset(); // survive a close operation! String content2 = IOUtils.toString(is); assertTrue(content.length() == 100); assertEquals(content, content2); } finally { Optional.ofNullable(is).ifPresent(ReleasableInputStream::release); } } @Test(expected = ClosedChannelException.class) public void negativeTestResetWithClosedFile() throws IOException { try (ResettableInputStream is = new ResettableInputStream(file)) { is.close(); is.reset(); } } @Test public void testMarkAndResetWithClosedFile() throws IOException { ResettableInputStream is = null; try { is = new ResettableInputStream(file).disableClose(); is.read(new byte[10]); is.mark(-1); String content = IOUtils.toString(is); is.close(); is.reset(); // survive a close operation! String content2 = IOUtils.toString(is); assertTrue(content.length() == 90); assertEquals(content, content2); } finally { Optional.ofNullable(is).ifPresent(ReleasableInputStream::release); } } @Test(expected = ClosedChannelException.class) public void testMarkAndResetClosedFileInputStream() throws IOException { try (ResettableInputStream is = new ResettableInputStream(new FileInputStream(file))) { is.close(); is.reset(); // cannot survive a close if not disabled } } }
1,680
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/waiters/WaiterConfigurationTest.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.core.internal.waiters; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; public class WaiterConfigurationTest { @Test public void overrideConfigurationNull_shouldUseDefaultValue() { WaiterConfiguration waiterConfiguration = new WaiterConfiguration(null); assertThat(waiterConfiguration.backoffStrategy()) .isEqualTo(FixedDelayBackoffStrategy.create(Duration.ofSeconds(5))); assertThat(waiterConfiguration.maxAttempts()).isEqualTo(3); assertThat(waiterConfiguration.waitTimeout()).isNull(); } @Test public void overrideConfigurationNotAllValuesProvided_shouldUseDefaultValue() { WaiterConfiguration waiterConfiguration = new WaiterConfiguration(WaiterOverrideConfiguration.builder() .backoffStrategy(BackoffStrategy.none()) .build()); assertThat(waiterConfiguration.backoffStrategy()) .isEqualTo(BackoffStrategy.none()); assertThat(waiterConfiguration.maxAttempts()).isEqualTo(3); assertThat(waiterConfiguration.waitTimeout()).isNull(); } @Test public void overrideConfigurationProvided_shouldTakesPrecedence() { WaiterConfiguration waiterConfiguration = new WaiterConfiguration(WaiterOverrideConfiguration.builder() .backoffStrategy(BackoffStrategy.none()) .maxAttempts(10) .waitTimeout(Duration.ofMinutes(3)) .build()); assertThat(waiterConfiguration.backoffStrategy()) .isEqualTo(BackoffStrategy.none()); assertThat(waiterConfiguration.maxAttempts()).isEqualTo(10); assertThat(waiterConfiguration.waitTimeout()).isEqualTo(Duration.ofMinutes(3)); } }
1,681
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/waiters/DefaultWaiterResponseTest.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.core.internal.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import org.testng.annotations.Test; import software.amazon.awssdk.core.waiters.WaiterResponse; public class DefaultWaiterResponseTest { @Test public void bothResponseAndExceptionPresent_shouldThrowException() { assertThatThrownBy(() -> DefaultWaiterResponse.<String>builder().exception(new RuntimeException("")) .response("foobar") .attemptsExecuted(1) .build()).hasMessageContaining("mutually exclusive"); } @Test public void missingAttemptsExecuted_shouldThrowException() { assertThatThrownBy(() -> DefaultWaiterResponse.<String>builder().response("foobar") .build()).hasMessageContaining("attemptsExecuted"); } @Test public void equalsHashcode() { WaiterResponse<String> response1 = DefaultWaiterResponse.<String>builder() .response("response") .attemptsExecuted(1) .build(); WaiterResponse<String> response2 = DefaultWaiterResponse.<String>builder() .response("response") .attemptsExecuted(1) .build(); WaiterResponse<String> response3 = DefaultWaiterResponse.<String>builder() .exception(new RuntimeException("test")) .attemptsExecuted(1) .build(); assertEquals(response1, response2); assertEquals(response1.hashCode(), response2.hashCode()); assertNotEquals(response1.hashCode(), response3.hashCode()); assertNotEquals(response1, response3); } @Test public void exceptionPresent() { RuntimeException exception = new RuntimeException("test"); WaiterResponse<String> response = DefaultWaiterResponse.<String>builder() .exception(exception) .attemptsExecuted(1) .build(); assertThat(response.matched().exception()).contains(exception); assertThat(response.matched().response()).isEmpty(); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void responsePresent() { WaiterResponse<String> response = DefaultWaiterResponse.<String>builder() .response("helloworld") .attemptsExecuted(2) .build(); assertThat(response.matched().response()).contains("helloworld"); assertThat(response.matched().exception()).isEmpty(); assertThat(response.attemptsExecuted()).isEqualTo(2); } }
1,682
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/waiters/WaiterExecutorTest.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.core.internal.waiters; import java.util.Arrays; import java.util.concurrent.atomic.LongAdder; import org.junit.jupiter.api.Test; import org.testng.Assert; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterAcceptor; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; class WaiterExecutorTest { @Test void largeMaxAttempts() { int expectedAttempts = 10_000; WaiterOverrideConfiguration conf = WaiterOverrideConfiguration.builder() .maxAttempts(expectedAttempts) .backoffStrategy(BackoffStrategy.none()) .build(); WaiterExecutor<Integer> sut = new WaiterExecutor<>(new WaiterConfiguration(conf), Arrays.asList( WaiterAcceptor.retryOnResponseAcceptor(c -> c < expectedAttempts), WaiterAcceptor.successOnResponseAcceptor(c -> c == expectedAttempts) )); LongAdder attemptCounter = new LongAdder(); sut.execute(() -> { attemptCounter.increment(); return attemptCounter.intValue(); }); Assert.assertEquals(attemptCounter.intValue(), expectedAttempts); } }
1,683
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/IdempotentTransformingAsyncResponseHandlerTest.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.core.internal.http; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.SdkHttpResponse; @RunWith(MockitoJUnitRunner.class) public class IdempotentTransformingAsyncResponseHandlerTest { private final AtomicInteger scope = new AtomicInteger(1); private final CompletableFuture<String> fakeFuture1 = CompletableFuture.completedFuture("one"); private final CompletableFuture<String> fakeFuture2 = CompletableFuture.completedFuture("two"); private IdempotentAsyncResponseHandler<String, Integer> handlerUnderTest; @Mock private TransformingAsyncResponseHandler<String> mockResponseHandler; @Mock private Publisher<ByteBuffer> mockPublisher; @Mock private SdkHttpResponse mockSdkHttpResponse; @Before public void instantiateHandler() { handlerUnderTest = IdempotentAsyncResponseHandler.create(mockResponseHandler, scope::get, (x, y) -> x < y + 10); } @Before public void stubMocks() { when(mockResponseHandler.prepare()).thenReturn(fakeFuture1).thenReturn(fakeFuture2); } @Test public void prepareDelegatesFirstTime() { assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); verify(mockResponseHandler).prepare(); verifyNoMoreInteractions(mockResponseHandler); } @Test public void onErrorDelegates() { RuntimeException e = new RuntimeException("boom"); handlerUnderTest.onError(e); verify(mockResponseHandler).onError(e); verifyNoMoreInteractions(mockResponseHandler); } @Test public void onStreamDelegates() { handlerUnderTest.onStream(mockPublisher); verify(mockResponseHandler).onStream(mockPublisher); verifyNoMoreInteractions(mockResponseHandler); } @Test public void onHeadersDelegates() { handlerUnderTest.onHeaders(mockSdkHttpResponse); verify(mockResponseHandler).onHeaders(mockSdkHttpResponse); verifyNoMoreInteractions(mockResponseHandler); } @Test public void prepare_unchangedScope_onlyDelegatesOnce() { assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); verify(mockResponseHandler).prepare(); verifyNoMoreInteractions(mockResponseHandler); } @Test public void prepare_scopeChangedButStillInRange_onlyDelegatesOnce() { assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); scope.set(2); assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); verify(mockResponseHandler).prepare(); verifyNoMoreInteractions(mockResponseHandler); } @Test public void prepare_scopeChangedOutOfRange_delegatesTwice() { assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture1); scope.set(11); assertThat(handlerUnderTest.prepare()).isSameAs(fakeFuture2); verify(mockResponseHandler, times(2)).prepare(); verifyNoMoreInteractions(mockResponseHandler); } @Test public void prepare_appearsToBeThreadSafe() { handlerUnderTest = IdempotentAsyncResponseHandler.create( mockResponseHandler, () -> { int result = scope.get(); try { Thread.sleep(10L); } catch (InterruptedException e) { fail(); } return result; }, Integer::equals); IntStream.range(0, 200).parallel().forEach(i -> handlerUnderTest.prepare()); verify(mockResponseHandler).prepare(); verifyNoMoreInteractions(mockResponseHandler); } }
1,684
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/MakeHttpRequestStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.client.config.SdkClientOption.SYNC_HTTP_CLIENT; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.timers.TimeoutTracker; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class MakeHttpRequestStageTest { @Mock private SdkHttpClient mockClient; private MakeHttpRequestStage stage; @Before public void setup() throws IOException { SdkClientConfiguration config = SdkClientConfiguration.builder().option(SYNC_HTTP_CLIENT, mockClient).build(); stage = new MakeHttpRequestStage(HttpClientDependencies.builder().clientConfiguration(config).build()); } @Test public void testExecute_contextContainsMetricCollector_addsChildToExecuteRequest() { SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .host("mybucket.s3.us-west-2.amazonaws.com") .protocol("https") .build(); MetricCollector mockCollector = mock(MetricCollector.class); MetricCollector childCollector = mock(MetricCollector.class); when(mockCollector.createChild(any(String.class))).thenReturn(childCollector); ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .originalRequest(ValidSdkObjects.sdkRequest()) .executionContext(executionContext) .build(); context.attemptMetricCollector(mockCollector); context.apiCallAttemptTimeoutTracker(mock(TimeoutTracker.class)); context.apiCallTimeoutTracker(mock(TimeoutTracker.class)); try { stage.execute(sdkRequest, context); } catch (Exception e) { // ignored, don't really care about successful execution of the stage in this case } finally { ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(mockClient).prepareRequest(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } } }
1,685
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/TimeoutExceptionHandlingStageTest.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.core.internal.http.pipeline.stages; 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.when; import java.io.IOException; import java.net.SocketException; import java.util.concurrent.ScheduledFuture; 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.core.Response; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkRequestOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.exception.AbortedException; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.http.timers.ApiCallTimeoutTracker; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.core.internal.http.timers.TimeoutTask; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class TimeoutExceptionHandlingStageTest { @Mock private RequestPipeline<SdkHttpFullRequest, Response<String>> requestPipeline; @Mock private TimeoutTask apiCallTimeoutTask; @Mock private TimeoutTask apiCallAttemptTimeoutTask; @Mock private ScheduledFuture scheduledFuture; private TimeoutExceptionHandlingStage<String> stage; @Before public void setup() { stage = new TimeoutExceptionHandlingStage<>(HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder().build()) .build(), requestPipeline); } @Test public void IOException_causedByApiCallTimeout_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new SocketException()); verifyExceptionThrown(InterruptedException.class); } @Test public void IOException_causedByApiCallAttemptTimeout_shouldThrowApiCallAttemptTimeoutException() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new IOException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); } @Test public void IOException_bothTimeouts_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new IOException()); verifyExceptionThrown(InterruptedException.class); } @Test public void IOException_notCausedByTimeouts_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new SocketException()); verifyExceptionThrown(SocketException.class); } @Test public void AbortedException_notCausedByTimeouts_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(AbortedException.class); } @Test public void AbortedException_causedByAttemptTimeout_shouldThrowApiCallAttemptTimeoutException() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); } @Test public void AbortedException_causedByCallTimeout_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.create("")); verifyExceptionThrown(InterruptedException.class); } @Test public void nonTimeoutCausedException_shouldPropagate() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(RuntimeException.class); } @Test public void interruptedException_notCausedByTimeouts_shouldPreserveInterruptFlag() throws Exception { when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(AbortedException.class); verifyInterruptStatusPreserved(); } @Test public void interruptedException_causedByApiCallTimeout_shouldPropagate() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(InterruptedException.class); } @Test public void interruptedException_causedByAttemptTimeout_shouldThrowApiAttempt() throws Exception { when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new InterruptedException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); verifyInterruptStatusClear(); } @Test public void interruptFlagWasSet_causedByAttemptTimeout_shouldThrowApiAttempt() throws Exception { Thread.currentThread().interrupt(); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); verifyInterruptStatusClear(); } @Test public void interruptFlagWasSet_causedByApiCallTimeout_shouldThrowInterruptException() throws Exception { Thread.currentThread().interrupt(); when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new RuntimeException()); verifyExceptionThrown(InterruptedException.class); verifyInterruptStatusPreserved(); } @Test public void apiCallAttemptTimeoutException_causedBySdkClientException_as_apiCallAttemptTimeoutTask_Caused_SdkClientException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(false); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(SdkClientException.create("")); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); } @Test public void interruptedException_causedByApiCallAttemptTimeoutTask() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(SdkClientException.class); verifyExceptionThrown(InterruptedException.class); } @Test public void abortedException_causedByApiCallAttemptTimeoutTask_shouldNotPropagate() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(false); when(apiCallAttemptTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(AbortedException.class); verifyExceptionThrown(ApiCallAttemptTimeoutException.class); } private void verifyInterruptStatusPreserved() { assertThat(Thread.currentThread().isInterrupted()).isTrue(); } private void verifyInterruptStatusClear() { assertThat(Thread.currentThread().isInterrupted()).isFalse(); } private void verifyExceptionThrown(Class exceptionToAssert) { RequestExecutionContext context = requestContext(); context.apiCallTimeoutTracker(new ApiCallTimeoutTracker(apiCallTimeoutTask, scheduledFuture)); context.apiCallAttemptTimeoutTracker(new ApiCallTimeoutTracker(apiCallAttemptTimeoutTask, scheduledFuture)); assertThatThrownBy(() -> stage.execute(ValidSdkObjects.sdkHttpFullRequest().build(), context)) .isExactlyInstanceOf(exceptionToAssert); } private RequestExecutionContext requestContext() { SdkRequestOverrideConfiguration.Builder configBuilder = SdkRequestOverrideConfiguration.builder(); SdkRequest originalRequest = NoopTestRequest.builder() .overrideConfiguration(configBuilder .build()) .build(); return RequestExecutionContext.builder() .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .originalRequest(originalRequest) .build(); } }
1,686
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/MergeCustomHeadersStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkRequestOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.ValidSdkObjects; @RunWith(Parameterized.class) public class MergeCustomHeadersStageTest { // List of headers that may appear only once in a request; i.e. is not a list of values. // Taken from https://github.com/apache/httpcomponents-client/blob/81c1bc4dc3ca5a3134c5c60e8beff08be2fd8792/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java#L69-L85 with modifications: // removed: accept-ranges, if-match, if-none-match, vary since it looks like they're defined as lists private static final Set<String> SINGLE_HEADERS = Stream.of("age", "authorization", "content-length", "content-location", "content-md5", "content-range", "content-type", "date", "etag", "expires", "from", "host", "if-modified-since", "if-range", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "range", "referer", "retry-after", "server", "user-agent") .collect(Collectors.toSet()); @Parameterized.Parameters(name = "Header = {0}") public static Collection<Object> data() { return Arrays.asList(SINGLE_HEADERS.toArray(new Object[0])); } @Parameterized.Parameter public String singleHeaderName; @Test public void singleHeader_inMarshalledRequest_overriddenOnClient() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder().build()); requestBuilder.putHeader(singleHeaderName, "marshaller"); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("client"); } @Test public void singleHeader_inMarshalledRequest_overriddenOnRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, Collections.emptyMap()) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); } @Test public void singleHeader_inClient_overriddenOnRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); } @Test public void singleHeader_inMarshalledRequest_inClient_inRequest() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, "request").build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); clientHeaders.put(singleHeaderName, Collections.singletonList("client")); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request"); } @Test public void singleHeader_inRequestAsList_keepsMultipleValues() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); requestBuilder.putHeader(singleHeaderName, "marshaller"); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder() .overrideConfiguration(SdkRequestOverrideConfiguration.builder() .putHeader(singleHeaderName, Arrays.asList("request", "request2", "request3")) .build()) .build()); Map<String, List<String>> clientHeaders = new HashMap<>(); HttpClientDependencies clientDeps = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, clientHeaders) .build()) .build(); MergeCustomHeadersStage stage = new MergeCustomHeadersStage(clientDeps); stage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(singleHeaderName)).containsExactly("request", "request2", "request3"); } private RequestExecutionContext requestContext(SdkRequest request) { ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(ValidSdkObjects.sdkHttpFullRequest().build()); return RequestExecutionContext.builder() .executionContext(executionContext) .originalRequest(request) .build(); } }
1,687
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/HttpChecksumStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.core.HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE; import static software.amazon.awssdk.core.HttpChecksumConstant.SIGNING_METHOD; import static software.amazon.awssdk.core.internal.signer.SigningMethod.UNSIGNED_PAYLOAD; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_MD5; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksumRequired; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class HttpChecksumStageTest { private static final String CHECKSUM_SPECS_HEADER = "x-amz-checksum-sha256"; private static final RequestBody REQUEST_BODY = RequestBody.fromString("TestBody"); private static final AsyncRequestBody ASYNC_REQUEST_BODY = AsyncRequestBody.fromString("TestBody"); private final HttpChecksumStage syncStage = new HttpChecksumStage(ClientType.SYNC); private final HttpChecksumStage asyncStage = new HttpChecksumStage(ClientType.ASYNC); @Test public void sync_md5Required_addsMd5Checksum_doesNotAddFlexibleChecksums() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isAsyncStreaming = false; RequestExecutionContext ctx = md5RequiredRequestContext(isAsyncStreaming); syncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(CONTENT_MD5)).containsExactly("9dzKaiLL99all2ZyHa76RA=="); assertThat(requestBuilder.firstMatchingHeader(HEADER_FOR_TRAILER_REFERENCE)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("Content-encoding")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-content-sha256")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_LENGTH)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CHECKSUM_SPECS_HEADER)).isEmpty(); } @Test public void async_nonStreaming_md5Required_addsMd5Checksum_doesNotAddFlexibleChecksums() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isAsyncStreaming = false; RequestExecutionContext ctx = md5RequiredRequestContext(isAsyncStreaming); asyncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(CONTENT_MD5)).containsExactly("9dzKaiLL99all2ZyHa76RA=="); assertThat(requestBuilder.firstMatchingHeader(HEADER_FOR_TRAILER_REFERENCE)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("Content-encoding")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-content-sha256")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_LENGTH)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CHECKSUM_SPECS_HEADER)).isEmpty(); } @Test public void async_streaming_md5Required_throws_IllegalArgumentException() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isAsyncStreaming = true; RequestExecutionContext ctx = md5RequiredRequestContext(isAsyncStreaming); Exception exception = assertThrows(IllegalArgumentException.class, () -> { asyncStage.execute(requestBuilder, ctx); }); assertThat(exception.getMessage()).isEqualTo("This operation requires a content-MD5 checksum, but one cannot be " + "calculated for non-blocking content."); } @Test public void sync_flexibleChecksumInTrailerRequired_addsFlexibleChecksumInTrailer_doesNotAddMd5ChecksumAndFlexibleChecksumInHeader() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isStreaming = true; RequestExecutionContext ctx = syncFlexibleChecksumRequiredRequestContext(isStreaming); syncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(HEADER_FOR_TRAILER_REFERENCE)).containsExactly(CHECKSUM_SPECS_HEADER); assertThat(requestBuilder.headers().get("Content-encoding")).containsExactly("aws-chunked"); assertThat(requestBuilder.headers().get("x-amz-content-sha256")).containsExactly("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(requestBuilder.headers().get("x-amz-decoded-content-length")).containsExactly("8"); assertThat(requestBuilder.headers().get(CONTENT_LENGTH)).containsExactly("86"); assertThat(requestBuilder.firstMatchingHeader(CONTENT_MD5)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CHECKSUM_SPECS_HEADER)).isEmpty(); } @Test public void async_flexibleChecksumInTrailerRequired_addsFlexibleChecksumInTrailer_doesNotAddMd5ChecksumAndFlexibleChecksumInHeader() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isStreaming = true; RequestExecutionContext ctx = asyncFlexibleChecksumRequiredRequestContext(isStreaming); asyncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(HEADER_FOR_TRAILER_REFERENCE)).containsExactly(CHECKSUM_SPECS_HEADER); assertThat(requestBuilder.headers().get("Content-encoding")).containsExactly("aws-chunked"); assertThat(requestBuilder.headers().get("x-amz-content-sha256")).containsExactly("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(requestBuilder.headers().get("x-amz-decoded-content-length")).containsExactly("8"); assertThat(requestBuilder.headers().get(CONTENT_LENGTH)).containsExactly("86"); assertThat(requestBuilder.firstMatchingHeader(CONTENT_MD5)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CHECKSUM_SPECS_HEADER)).isEmpty(); } @Test public void sync_flexibleChecksumInHeaderRequired_addsFlexibleChecksumInHeader_doesNotAddMd5ChecksumAndFlexibleChecksumInTrailer() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isStreaming = false; RequestExecutionContext ctx = syncFlexibleChecksumRequiredRequestContext(isStreaming); syncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(CHECKSUM_SPECS_HEADER)).containsExactly("/T5YuTxNWthvWXg+TJMwl60XKcAnLMrrOZe/jA9Y+eI="); assertThat(requestBuilder.firstMatchingHeader(HEADER_FOR_TRAILER_REFERENCE)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("Content-encoding")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-content-sha256")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_LENGTH)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_MD5)).isEmpty(); } @Test public void async_flexibleChecksumInHeaderRequired_addsFlexibleChecksumInHeader_doesNotAddMd5ChecksumAndFlexibleChecksumInTrailer() throws Exception { SdkHttpFullRequest.Builder requestBuilder = createHttpRequestBuilder(); boolean isStreaming = false; RequestExecutionContext ctx = asyncFlexibleChecksumRequiredRequestContext(isStreaming); asyncStage.execute(requestBuilder, ctx); assertThat(requestBuilder.headers().get(CHECKSUM_SPECS_HEADER)).containsExactly("/T5YuTxNWthvWXg+TJMwl60XKcAnLMrrOZe/jA9Y+eI="); assertThat(requestBuilder.firstMatchingHeader(HEADER_FOR_TRAILER_REFERENCE)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("Content-encoding")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-content-sha256")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_LENGTH)).isEmpty(); assertThat(requestBuilder.firstMatchingHeader(CONTENT_MD5)).isEmpty(); } private SdkHttpFullRequest.Builder createHttpRequestBuilder() { return SdkHttpFullRequest.builder().contentStreamProvider(REQUEST_BODY.contentStreamProvider()); } private RequestExecutionContext md5RequiredRequestContext(boolean isAsyncStreaming) { ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkInternalExecutionAttribute.HTTP_CHECKSUM_REQUIRED, HttpChecksumRequired.create()) .build(); InterceptorContext interceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(ValidSdkObjects.sdkHttpFullRequest().build()) .requestBody(REQUEST_BODY) .build(); return createRequestExecutionContext(executionAttributes, interceptorContext, isAsyncStreaming); } private RequestExecutionContext syncFlexibleChecksumRequiredRequestContext(boolean isStreaming) { ChecksumSpecs checksumSpecs = ChecksumSpecs.builder() .headerName(CHECKSUM_SPECS_HEADER) // true = trailer, false = header .isRequestStreaming(isStreaming) .algorithm(Algorithm.SHA256) .build(); ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, checksumSpecs) .put(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC) .put(SIGNING_METHOD, UNSIGNED_PAYLOAD) .build(); InterceptorContext interceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(ValidSdkObjects.sdkHttpFullRequest().build()) .requestBody(REQUEST_BODY) .build(); return createRequestExecutionContext(executionAttributes, interceptorContext, false); } private RequestExecutionContext asyncFlexibleChecksumRequiredRequestContext(boolean isStreaming) { ChecksumSpecs checksumSpecs = ChecksumSpecs.builder() .headerName(CHECKSUM_SPECS_HEADER) // true = trailer, false = header .isRequestStreaming(isStreaming) .algorithm(Algorithm.SHA256) .build(); ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, checksumSpecs) .put(SdkExecutionAttribute.CLIENT_TYPE, ClientType.ASYNC) .put(SIGNING_METHOD, UNSIGNED_PAYLOAD) .build(); InterceptorContext.Builder interceptorContextBuilder = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(ValidSdkObjects.sdkHttpFullRequest().build()) .requestBody(REQUEST_BODY); if (isStreaming) { interceptorContextBuilder.asyncRequestBody(ASYNC_REQUEST_BODY); } return createRequestExecutionContext(executionAttributes, interceptorContextBuilder.build(), isStreaming); } private RequestExecutionContext createRequestExecutionContext(ExecutionAttributes executionAttributes, InterceptorContext interceptorContext, boolean isAsyncStreaming) { ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(executionAttributes) .interceptorContext(interceptorContext) .build(); RequestExecutionContext.Builder builder = RequestExecutionContext.builder() .executionContext(executionContext) .originalRequest(NoopTestRequest.builder().build()); if (isAsyncStreaming) { builder.requestProvider(ASYNC_REQUEST_BODY); } return builder.build(); } }
1,688
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/RetryableStageAdaptiveModeTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.Response; 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.core.exception.SdkException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.retry.RateLimitingTokenBucket; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.HttpStatusCode; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.metrics.NoOpMetricCollector; public class RetryableStageAdaptiveModeTest { private RateLimitingTokenBucket tokenBucket; private RequestPipeline<SdkHttpFullRequest, Response<Object>> mockChildPipeline; private RetryableStage<Object> retryableStage; @BeforeEach public void setup() throws Exception { tokenBucket = spy(RateLimitingTokenBucket.class); mockChildPipeline = mock(RequestPipeline.class); } @Test public void execute_acquiresToken() throws Exception { retryableStage = createStage(false); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()); verify(tokenBucket).acquire(1.0, false); } @Test public void execute_fastFailEnabled_propagatesSettingToBucket() throws Exception { retryableStage = createStage(true); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()); verify(tokenBucket).acquire(1.0, true); } @Test public void execute_retryModeStandard_doesNotAcquireToken() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.STANDARD).build(); mockChildResponse(createSuccessResponse()); retryableStage = createStage(retryPolicy); retryableStage.execute(createHttpRequest(), createExecutionContext()); verifyNoMoreInteractions(tokenBucket); } @Test public void execute_retryModeLegacy_doesNotAcquireToken() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.LEGACY).build(); mockChildResponse(createSuccessResponse()); retryableStage = createStage(retryPolicy); retryableStage.execute(createHttpRequest(), createExecutionContext()); verifyNoMoreInteractions(tokenBucket); } @Test public void execute_acquireReturnsFalse_throws() { when(tokenBucket.acquire(anyDouble(), anyBoolean())).thenReturn(false); retryableStage = createStage(false); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to acquire a send token"); } @Test public void execute_responseSuccessful_updatesWithThrottlingFalse() throws Exception { retryableStage = createStage(false); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()); verify(tokenBucket).updateClientSendingRate(false); verify(tokenBucket, never()).updateClientSendingRate(true); } @Test public void execute_nonThrottlingServiceException_doesNotUpdateRate() throws Exception { SdkServiceException exception = SdkServiceException.builder() .statusCode(500) .build(); mockChildResponse(exception); retryableStage = createStage(false); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext)) .isInstanceOf(SdkServiceException.class); verify(tokenBucket, never()).updateClientSendingRate(anyBoolean()); } @Test public void execute_throttlingServiceException_updatesRate() throws Exception { SdkServiceException exception = SdkServiceException.builder() .statusCode(HttpStatusCode.THROTTLING) .build(); RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .numRetries(0) .build(); mockChildResponse(exception); retryableStage = createStage(retryPolicy); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext)) .isInstanceOf(SdkServiceException.class); verify(tokenBucket).updateClientSendingRate(true); verify(tokenBucket, never()).updateClientSendingRate(false); } @Test public void execute_unsuccessfulResponse_nonThrottlingError_doesNotUpdateRate() throws Exception { retryableStage = createStage(false); SdkServiceException error = SdkServiceException.builder() .statusCode(500) .build(); mockChildResponse(createUnsuccessfulResponse(error)); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext)) .isInstanceOf(SdkServiceException.class); verify(tokenBucket, never()).updateClientSendingRate(anyBoolean()); } @Test public void execute_unsuccessfulResponse_throttlingError_updatesRate() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .numRetries(0) .build(); retryableStage = createStage(retryPolicy); SdkServiceException error = SdkServiceException.builder() .statusCode(HttpStatusCode.THROTTLING) .build(); mockChildResponse(createUnsuccessfulResponse(error)); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext)) .isInstanceOf(SdkServiceException.class); verify(tokenBucket).updateClientSendingRate(true); verify(tokenBucket, never()).updateClientSendingRate(false); } private RetryableStage<Object> createStage(boolean failFast) { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .fastFailRateLimiting(failFast) .build(); return createStage(retryPolicy); } private RetryableStage<Object> createStage(RetryPolicy retryPolicy) { return new RetryableStage<>(clientDependencies(retryPolicy), mockChildPipeline, tokenBucket); } private Response<Object> createSuccessResponse() { return Response.builder() .isSuccess(true) .build(); } public Response<Object> createUnsuccessfulResponse(SdkException exception) { return Response.builder() .isSuccess(false) .exception(exception) .build(); } private HttpClientDependencies clientDependencies(RetryPolicy retryPolicy) { SdkClientConfiguration clientConfiguration = SdkClientConfiguration.builder() .option(SdkClientOption.RETRY_POLICY, retryPolicy) .build(); return HttpClientDependencies.builder() .clientConfiguration(clientConfiguration) .build(); } private static RequestExecutionContext createExecutionContext() { return RequestExecutionContext.builder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .metricCollector(NoOpMetricCollector.create()) .build()) .build(); } private static SdkHttpFullRequest createHttpRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("https") .host("amazon.com") .build(); } private void mockChildResponse(Response<Object> response) throws Exception { when(mockChildPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))).thenReturn(response); } private void mockChildResponse(Exception error) throws Exception { when(mockChildPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))).thenThrow(error); } }
1,689
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/ApiCallTimeoutTrackingStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; 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.core.Response; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkRequestOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.AbortedException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.ThreadFactoryBuilder; @RunWith(MockitoJUnitRunner.class) public class ApiCallTimeoutTrackingStageTest { @Mock private RequestPipeline<SdkHttpFullRequest, Response<Void>> wrapped; private ApiCallTimeoutTrackingStage<Void> stage; @Before public void setUp() throws Exception { final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder() .threadNamePrefix("sdk-ScheduledExecutor-test").build()); stage = new ApiCallTimeoutTrackingStage<>(HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder() .option (SdkClientOption .SCHEDULED_EXECUTOR_SERVICE, timeoutExecutor) .build()) .build(), wrapped); } @Test public void timedOut_shouldThrowApiCallTimeoutException() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> { Thread.sleep(600); return null; }); RequestExecutionContext context = requestContext(500); assertThatThrownBy(() -> stage.execute(mock(SdkHttpFullRequest.class), context)).isInstanceOf(ApiCallTimeoutException .class); assertThat(context.apiCallTimeoutTracker().hasExecuted()).isTrue(); } @Test public void timeoutDisabled_shouldNotExecuteTimer() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); RequestExecutionContext context = requestContext(0); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(context.apiCallTimeoutTracker().hasExecuted()).isFalse(); } @Test(expected = RuntimeException.class) public void nonTimerInterruption_RuntimeExceptionThrown_interruptFlagIsPreserved() throws Exception { nonTimerInterruption_interruptFlagIsPreserved(new RuntimeException()); } @Test(expected = AbortedException.class) public void nonTimerInterruption_InterruptedExceptionThrown_interruptFlagIsPreserved() throws Exception { nonTimerInterruption_interruptFlagIsPreserved(new InterruptedException()); } /** * Test to ensure that if the execution *did not* expire but the * interrupted flag is set that it's not cleared by * ApiCallTimedStage because it's not an interruption by the timer. * * @param exceptionToThrow The exception to throw from the wrapped pipeline. */ private void nonTimerInterruption_interruptFlagIsPreserved(final Exception exceptionToThrow) throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> { Thread.currentThread().interrupt(); throw exceptionToThrow; }); RequestExecutionContext context = requestContext(500); try { stage.execute(mock(SdkHttpFullRequest.class), context); fail("No exception"); } finally { assertThat(Thread.interrupted()).isTrue(); assertThat(context.apiCallTimeoutTracker().hasExecuted()).isFalse(); } } private RequestExecutionContext requestContext(long timeout) { SdkRequestOverrideConfiguration.Builder configBuilder = SdkRequestOverrideConfiguration.builder(); if (timeout > 0) { configBuilder.apiCallTimeout(Duration.ofMillis(timeout)); } SdkRequest originalRequest = NoopTestRequest.builder() .overrideConfiguration(configBuilder .build()) .build(); return RequestExecutionContext.builder() .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .originalRequest(originalRequest) .build(); } }
1,690
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/QueryParametersToBodyStageTest.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.core.internal.http.pipeline.stages; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.SdkProtocolMetadata; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.IoUtils; public class QueryParametersToBodyStageTest { public static final URI HTTP_LOCALHOST = URI.create("http://localhost:8080"); private QueryParametersToBodyStage stage; private SdkHttpFullRequest.Builder requestBuilder; @BeforeEach public void setup() { stage = new QueryParametersToBodyStage(); requestBuilder = SdkHttpFullRequest.builder() .protocol(Protocol.HTTPS.toString()) .method(SdkHttpMethod.POST) .putRawQueryParameter("key", singletonList("value")) .uri(HTTP_LOCALHOST); } private void verifyParametersMovedToBody(SdkHttpFullRequest output) throws Exception { assertThat(output.rawQueryParameters()).hasSize(0); assertThat(output.headers()) .containsKey("Content-Length") .containsEntry("Content-Type", singletonList("application/x-www-form-urlencoded; charset=utf-8")); assertThat(output.contentStreamProvider()).isNotEmpty(); String bodyContent = new String(IoUtils.toByteArray(output.contentStreamProvider().get().newStream())); assertThat(bodyContent).isEqualTo("key=value"); } private void verifyParametersUnaltered(SdkHttpFullRequest output, int numOfParams) { assertThat(output.rawQueryParameters()).hasSize(numOfParams); assertThat(output.headers()).isEmpty(); } @Test public void postRequestWithNoBody_queryProtocol_parametersAreMovedToTheBody() throws Exception { RequestExecutionContext requestExecutionContext = createRequestExecutionContext("query"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); verifyParametersMovedToBody(output); } @Test public void postRequestWithNoBody_ec2Protocol_parametersAreMovedToTheBody() throws Exception { RequestExecutionContext requestExecutionContext = createRequestExecutionContext("ec2"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); verifyParametersMovedToBody(output); } @Test public void postRequestWithNoBody_nonQueryProtocol_isUnaltered() throws Exception { RequestExecutionContext requestExecutionContext = createRequestExecutionContext("json"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); int numOfParams = 1; verifyParametersUnaltered(output, numOfParams); assertThat(output.contentStreamProvider()).isEmpty(); } @Test public void nonPostRequestsWithNoBodyAreUnaltered() { Stream.of(SdkHttpMethod.values()) .filter(m -> !m.equals(SdkHttpMethod.POST)) .forEach(method -> { try { nonPostRequestsUnaltered(method); } catch (Exception e) { fail("Exception thrown during stage execution"); } }); } @Test public void postWithContentIsUnaltered() throws Exception { byte[] contentBytes = "hello".getBytes(StandardCharsets.UTF_8); ContentStreamProvider contentProvider = () -> new ByteArrayInputStream(contentBytes); requestBuilder = requestBuilder.contentStreamProvider(contentProvider); RequestExecutionContext requestExecutionContext = createRequestExecutionContext("query"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); int numOfParams = 1; verifyParametersUnaltered(output, numOfParams); assertThat(IoUtils.toByteArray(output.contentStreamProvider().get().newStream())).isEqualTo(contentBytes); } @Test public void onlyAlterRequestsIfParamsArePresent() throws Exception { requestBuilder = requestBuilder.clearQueryParameters(); RequestExecutionContext requestExecutionContext = createRequestExecutionContext("query"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); int numOfParams = 0; verifyParametersUnaltered(output, numOfParams); assertThat(output.contentStreamProvider()).isEmpty(); } private void nonPostRequestsUnaltered(SdkHttpMethod method) throws Exception { requestBuilder = requestBuilder.method(method); RequestExecutionContext requestExecutionContext = createRequestExecutionContext("query"); SdkHttpFullRequest output = stage.execute(requestBuilder, requestExecutionContext).build(); int numOfParams = 1; verifyParametersUnaltered(output, numOfParams); assertThat(output.contentStreamProvider()).isEmpty(); } private RequestExecutionContext createRequestExecutionContext(String serviceProtocol) { ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkInternalExecutionAttribute.PROTOCOL_METADATA, new TestProtocolMetadata(serviceProtocol)) .build(); ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(executionAttributes) .build(); return RequestExecutionContext.builder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .build(); } private final class TestProtocolMetadata implements SdkProtocolMetadata { private String serviceProtocol; TestProtocolMetadata(String serviceProtocol) { this.serviceProtocol = serviceProtocol; } @Override public String serviceProtocol() { return serviceProtocol; } } }
1,691
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/ApiCallAttemptTimeoutTrackingStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE; import java.time.Duration; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; 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.core.Response; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkRequestOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.http.timers.ApiCallTimeoutTracker; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.core.internal.http.timers.NoOpTimeoutTracker; import software.amazon.awssdk.http.SdkHttpFullRequest; @RunWith(MockitoJUnitRunner.class) public class ApiCallAttemptTimeoutTrackingStageTest { @Mock private RequestPipeline<SdkHttpFullRequest, Response<Void>> wrapped; @Mock private ScheduledExecutorService timeoutExecutor; @Mock private ScheduledFuture scheduledFuture; private ApiCallAttemptTimeoutTrackingStage<Void> stage; @Before public void setUp() throws Exception { stage = new ApiCallAttemptTimeoutTrackingStage<>(HttpClientDependencies.builder() .clientConfiguration( SdkClientConfiguration.builder() .option(SCHEDULED_EXECUTOR_SERVICE, timeoutExecutor) .build()) .build(), wrapped); } @Test public void timeoutEnabled_shouldHaveTracker() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); when(timeoutExecutor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(scheduledFuture); RequestExecutionContext context = requestContext(500); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(scheduledFuture.isDone()).isFalse(); assertThat(context.apiCallAttemptTimeoutTracker()).isInstanceOf(ApiCallTimeoutTracker.class); } @Test public void timeoutDisabled_shouldNotExecuteTimer() throws Exception { when(wrapped.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenAnswer(invocationOnMock -> null); RequestExecutionContext context = requestContext(0); stage.execute(mock(SdkHttpFullRequest.class), context); assertThat(context.apiCallAttemptTimeoutTracker()).isInstanceOf(NoOpTimeoutTracker.class); assertThat(context.apiCallAttemptTimeoutTracker().isEnabled()).isFalse(); assertThat(context.apiCallAttemptTimeoutTracker().hasExecuted()).isFalse(); } private RequestExecutionContext requestContext(long timeout) { SdkRequestOverrideConfiguration.Builder configBuilder = SdkRequestOverrideConfiguration.builder(); if (timeout > 0) { configBuilder.apiCallAttemptTimeout(Duration.ofMillis(timeout)); } SdkRequest originalRequest = NoopTestRequest.builder() .overrideConfiguration(configBuilder .build()) .build(); return RequestExecutionContext.builder() .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .originalRequest(originalRequest) .build(); } }
1,692
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/AsyncApiCallTimeoutTrackingStageTest.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.core.internal.http.pipeline.stages; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URI; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; 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.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.core.internal.util.CapacityManager; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import utils.ValidSdkObjects; /** * Unit tests for {@link AsyncApiCallTimeoutTrackingStage}. */ @RunWith(MockitoJUnitRunner.class) public class AsyncApiCallTimeoutTrackingStageTest { private final long TIMEOUT_MILLIS = 1234; @Mock private RequestPipeline<SdkHttpFullRequest, CompletableFuture> requestPipeline; @Mock private ScheduledExecutorService executorService; private SdkClientConfiguration configuration; private HttpClientDependencies dependencies; @Mock private CapacityManager capacityManager; private SdkHttpFullRequest httpRequest; private RequestExecutionContext requestExecutionContext; private SdkRequest sdkRequest = NoopTestRequest.builder().build(); @Before public void methodSetup() throws Exception { configuration = SdkClientConfiguration.builder() .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE, executorService) .option(SdkClientOption.API_CALL_TIMEOUT, Duration.ofMillis(TIMEOUT_MILLIS)) .build(); dependencies = HttpClientDependencies.builder() .clientConfiguration(configuration) .build(); httpRequest = SdkHttpFullRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .build(); requestExecutionContext = RequestExecutionContext.builder() .originalRequest(sdkRequest) .executionContext(ClientExecutionAndRequestTimerTestUtils .executionContext(ValidSdkObjects.sdkHttpFullRequest().build())) .build(); when(requestPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))) .thenReturn(new CompletableFuture()); when(executorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(mock(ScheduledFuture.class)); } @Test @SuppressWarnings("unchecked") public void testSchedulesTheTimeoutUsingSuppliedExecutorService() throws Exception { AsyncApiCallTimeoutTrackingStage apiCallTimeoutTrackingStage = new AsyncApiCallTimeoutTrackingStage(dependencies, requestPipeline); apiCallTimeoutTrackingStage.execute(httpRequest, requestExecutionContext); verify(executorService) .schedule(any(Runnable.class), eq(TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS)); } }
1,693
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/ExceptionReportingUtilsTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.ExecutionContext; 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.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.stages.utils.ExceptionReportingUtils; import software.amazon.awssdk.core.signer.NoOpSigner; import utils.ValidSdkObjects; public class ExceptionReportingUtilsTest { @Test public void onExecutionFailureThrowException_shouldSwallow() { RequestExecutionContext context = context(new ThrowErrorOnExecutionFailureInterceptor()); assertThat(ExceptionReportingUtils.reportFailureToInterceptors(context, SdkClientException.create("test"))) .isExactlyInstanceOf(SdkClientException.class); } @Test public void modifyException_shouldReturnModifiedException() { ApiCallTimeoutException modifiedException = ApiCallTimeoutException.create(1000); RequestExecutionContext context = context(new ModifyExceptionInterceptor(modifiedException)); assertThat(ExceptionReportingUtils.reportFailureToInterceptors(context, SdkClientException.create("test"))) .isEqualTo(modifiedException); } public RequestExecutionContext context(ExecutionInterceptor... executionInterceptors) { List<ExecutionInterceptor> interceptors = Arrays.asList(executionInterceptors); ExecutionInterceptorChain executionInterceptorChain = new ExecutionInterceptorChain(interceptors); return RequestExecutionContext.builder() .executionContext(ExecutionContext.builder() .signer(new NoOpSigner()) .executionAttributes(new ExecutionAttributes()) .interceptorContext(InterceptorContext.builder() .request(ValidSdkObjects.sdkRequest()) .build()) .interceptorChain(executionInterceptorChain) .build()) .originalRequest(ValidSdkObjects.sdkRequest()) .build(); } private static class ThrowErrorOnExecutionFailureInterceptor implements ExecutionInterceptor { @Override public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { throw new RuntimeException("OOPS"); } } private static class ModifyExceptionInterceptor implements ExecutionInterceptor { private final Exception exceptionToThrow; private ModifyExceptionInterceptor(Exception exceptionToThrow) { this.exceptionToThrow = exceptionToThrow; } @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { return exceptionToThrow; } } }
1,694
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/MakeAsyncHttpRequestStageTest.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.core.internal.http.pipeline.stages; 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.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_ATTEMPT_TIMEOUT; import static software.amazon.awssdk.core.client.config.SdkClientOption.ASYNC_HTTP_CLIENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.combinedAsyncResponseHandler; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class MakeAsyncHttpRequestStageTest { @Mock private SdkAsyncHttpClient sdkAsyncHttpClient; @Mock private ScheduledExecutorService timeoutExecutor; private CompletableFuture<Void> clientExecuteFuture = CompletableFuture.completedFuture(null); @Mock private ScheduledFuture future; private MakeAsyncHttpRequestStage stage; @Before public void setup() { when(sdkAsyncHttpClient.execute(any())).thenReturn(clientExecuteFuture); when(timeoutExecutor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(future); } @Test public void apiCallAttemptTimeoutEnabled_shouldInvokeExecutor() throws Exception { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(Duration.ofMillis(1000))); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); stage.execute(requestFuture, requestContext()); verify(timeoutExecutor, times(1)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); } @Test public void apiCallAttemptTimeoutNotEnabled_shouldNotInvokeExecutor() throws Exception { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(null)); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); stage.execute(requestFuture, requestContext()); verify(timeoutExecutor, never()).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); } @Test public void testExecute_contextContainsMetricCollector_addsChildToExecuteRequest() { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(null)); SdkHttpFullRequest sdkHttpRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .host("mybucket.s3.us-west-2.amazonaws.com") .protocol("https") .build(); MetricCollector mockCollector = mock(MetricCollector.class); MetricCollector childCollector = mock(MetricCollector.class); when(mockCollector.createChild(any(String.class))).thenReturn(childCollector); ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .originalRequest(ValidSdkObjects.sdkRequest()) .executionContext(executionContext) .build(); context.attemptMetricCollector(mockCollector); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture(sdkHttpRequest); try { stage.execute(requestFuture, context); } catch (Exception e) { e.printStackTrace(); // ignored, don't really care about successful execution of the stage in this case } finally { ArgumentCaptor<AsyncExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(sdkAsyncHttpClient).execute(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } } @Test public void execute_handlerFutureCompletedNormally_futureCompletionExecutorRejectsWhenCompleteAsync_futureCompletedSynchronously() { ExecutorService mockExecutor = mock(ExecutorService.class); doThrow(new RejectedExecutionException("Busy")).when(mockExecutor).execute(any(Runnable.class)); SdkClientConfiguration config = SdkClientConfiguration.builder() .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, mockExecutor) .option(ASYNC_HTTP_CLIENT, sdkAsyncHttpClient) .build(); HttpClientDependencies dependencies = HttpClientDependencies.builder().clientConfiguration(config).build(); TransformingAsyncResponseHandler mockHandler = mock(TransformingAsyncResponseHandler.class); CompletableFuture prepareFuture = new CompletableFuture(); when(mockHandler.prepare()).thenReturn(prepareFuture); stage = new MakeAsyncHttpRequestStage<>(mockHandler, dependencies); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); CompletableFuture executeFuture = stage.execute(requestFuture, requestContext()); long testThreadId = Thread.currentThread().getId(); CompletableFuture afterWhenComplete = executeFuture.whenComplete((r, t) -> assertThat(Thread.currentThread().getId()).isEqualTo(testThreadId)); prepareFuture.complete(null); afterWhenComplete.join(); verify(mockExecutor).execute(any(Runnable.class)); } @Test public void execute_handlerFutureCompletedExceptionally_doesNotAttemptSynchronousComplete() { String threadNamePrefix = "async-handle-test"; ExecutorService mockExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().threadNamePrefix(threadNamePrefix).build()); SdkClientConfiguration config = SdkClientConfiguration.builder() .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, mockExecutor) .option(ASYNC_HTTP_CLIENT, sdkAsyncHttpClient) .build(); HttpClientDependencies dependencies = HttpClientDependencies.builder().clientConfiguration(config).build(); TransformingAsyncResponseHandler mockHandler = mock(TransformingAsyncResponseHandler.class); CompletableFuture prepareFuture = spy(new CompletableFuture()); when(mockHandler.prepare()).thenReturn(prepareFuture); stage = new MakeAsyncHttpRequestStage<>(mockHandler, dependencies); CompletableFuture<SdkHttpFullRequest> requestFuture = CompletableFuture.completedFuture( ValidSdkObjects.sdkHttpFullRequest().build()); CompletableFuture executeFuture = stage.execute(requestFuture, requestContext()); try { CompletableFuture afterHandle = executeFuture.handle((r, t) -> assertThat(Thread.currentThread().getName()).startsWith(threadNamePrefix)); prepareFuture.completeExceptionally(new RuntimeException("parse error")); afterHandle.join(); assertThatThrownBy(executeFuture::join) .hasCauseInstanceOf(RuntimeException.class) .hasMessageContaining("parse error"); verify(prepareFuture, times(0)).whenComplete(any()); } finally { mockExecutor.shutdown(); } } private HttpClientDependencies clientDependencies(Duration timeout) { SdkClientConfiguration configuration = SdkClientConfiguration.builder() .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .option(ASYNC_HTTP_CLIENT, sdkAsyncHttpClient) .option(SCHEDULED_EXECUTOR_SERVICE, timeoutExecutor) .option(API_CALL_ATTEMPT_TIMEOUT, timeout) .build(); return HttpClientDependencies.builder() .clientConfiguration(configuration) .build(); } private RequestExecutionContext requestContext() { ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(ValidSdkObjects.sdkHttpFullRequest().build()); return RequestExecutionContext.builder() .executionContext(executionContext) .originalRequest(NoopTestRequest.builder().build()) .build(); } }
1,695
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/AsyncRetryableStageAdaptiveModeTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.time.Duration; import java.util.OptionalDouble; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.Response; 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.core.exception.SdkException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.internal.http.pipeline.RequestPipeline; import software.amazon.awssdk.core.internal.retry.RateLimitingTokenBucket; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.HttpStatusCode; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.metrics.NoOpMetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; @RunWith(MockitoJUnitRunner.class) public class AsyncRetryableStageAdaptiveModeTest { @Spy private RateLimitingTokenBucket tokenBucket; private AsyncRetryableStage<Object> retryableStage; @Mock private RequestPipeline<SdkHttpFullRequest, CompletableFuture<Response<Object>>> mockChildPipeline; @Mock private ScheduledExecutorService scheduledExecutorService; @Before public void setup() throws Exception { when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer((Answer<ScheduledFuture<?>>) invocationOnMock -> { Runnable runnable = invocationOnMock.getArgument(0, Runnable.class); runnable.run(); return null; }); } @Test public void execute_acquiresToken() throws Exception { retryableStage = createStage(false); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()).join(); verify(tokenBucket).acquireNonBlocking(1.0, false); } @Test public void execute_acquireReturnsNonZeroValue_waitsForGivenTime() throws Exception { retryableStage = createStage(false); mockChildResponse(createSuccessResponse()); Duration waitTime = Duration.ofSeconds(3); when(tokenBucket.acquireNonBlocking(anyDouble(), anyBoolean())).thenReturn(OptionalDouble.of(waitTime.getSeconds())); retryableStage.execute(createHttpRequest(), createExecutionContext()).join(); verify(scheduledExecutorService).schedule(any(Runnable.class), eq(waitTime.toMillis()), eq(TimeUnit.MILLISECONDS)); } @Test public void execute_fastFailEnabled_propagatesSettingToBucket() throws Exception { retryableStage = createStage(true); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()).join(); verify(tokenBucket).acquireNonBlocking(1.0, true); } @Test public void execute_retryModeStandard_doesNotAcquireToken() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.STANDARD).build(); mockChildResponse(createSuccessResponse()); retryableStage = createStage(retryPolicy); retryableStage.execute(createHttpRequest(), createExecutionContext()).join(); verifyNoMoreInteractions(tokenBucket); } @Test public void execute_retryModeLegacy_doesNotAcquireToken() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.LEGACY).build(); mockChildResponse(createSuccessResponse()); retryableStage = createStage(retryPolicy); retryableStage.execute(createHttpRequest(), createExecutionContext()).join(); verifyNoMoreInteractions(tokenBucket); } @Test public void execute_acquireReturnsFalse_throws() throws Exception { when(tokenBucket.acquireNonBlocking(anyDouble(), anyBoolean())).thenReturn(OptionalDouble.empty()); retryableStage = createStage(false); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to acquire a send token"); } @Test public void execute_responseSuccessful_updatesWithThrottlingFalse() throws Exception { retryableStage = createStage(false); mockChildResponse(createSuccessResponse()); retryableStage.execute(createHttpRequest(), createExecutionContext()); verify(tokenBucket).updateClientSendingRate(false); verify(tokenBucket, never()).updateClientSendingRate(true); } @Test public void execute_nonThrottlingServiceException_doesNotUpdateRate() throws Exception { SdkServiceException exception = SdkServiceException.builder() .statusCode(500) .build(); mockChildResponse(exception); retryableStage = createStage(false); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(SdkServiceException.class); verify(tokenBucket, never()).updateClientSendingRate(anyBoolean()); } @Test public void execute_throttlingServiceException_updatesRate() throws Exception { SdkServiceException exception = SdkServiceException.builder() .statusCode(HttpStatusCode.THROTTLING) .build(); RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .numRetries(0) .build(); mockChildResponse(exception); retryableStage = createStage(retryPolicy); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(SdkServiceException.class); verify(tokenBucket).updateClientSendingRate(true); verify(tokenBucket, never()).updateClientSendingRate(false); } @Test public void execute_errorShouldNotBeWrapped() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .numRetries(0) .build(); mockChildResponse(new OutOfMemoryError()); retryableStage = createStage(retryPolicy); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(Error.class); } @Test public void execute_unsuccessfulResponse_nonThrottlingError_doesNotUpdateRate() throws Exception { retryableStage = createStage(false); SdkServiceException error = SdkServiceException.builder() .statusCode(500) .build(); mockChildResponse(createUnsuccessfulResponse(error)); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(SdkServiceException.class); verify(tokenBucket, never()).updateClientSendingRate(anyBoolean()); } @Test public void execute_unsuccessfulResponse_throttlingError_updatesRate() throws Exception { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .numRetries(0) .build(); retryableStage = createStage(retryPolicy); SdkServiceException error = SdkServiceException.builder() .statusCode(HttpStatusCode.THROTTLING) .build(); mockChildResponse(createUnsuccessfulResponse(error)); SdkHttpFullRequest httpRequest = createHttpRequest(); RequestExecutionContext executionContext = createExecutionContext(); assertThatThrownBy(() -> retryableStage.execute(httpRequest, executionContext).join()) .hasCauseInstanceOf(SdkServiceException.class); verify(tokenBucket).updateClientSendingRate(true); verify(tokenBucket, never()).updateClientSendingRate(false); } private AsyncRetryableStage<Object> createStage(boolean failFast) { RetryPolicy retryPolicy = RetryPolicy.builder(RetryMode.ADAPTIVE) .fastFailRateLimiting(failFast) .build(); return createStage(retryPolicy); } private AsyncRetryableStage<Object> createStage(RetryPolicy retryPolicy) { return new AsyncRetryableStage<>(null, clientDependencies(retryPolicy), mockChildPipeline, tokenBucket); } private Response<Object> createSuccessResponse() { return Response.builder() .isSuccess(true) .build(); } public Response<Object> createUnsuccessfulResponse(SdkException exception) { return Response.builder() .isSuccess(false) .exception(exception) .build(); } private HttpClientDependencies clientDependencies(RetryPolicy retryPolicy) { SdkClientConfiguration clientConfiguration = SdkClientConfiguration.builder() .option(SdkClientOption.RETRY_POLICY, retryPolicy) .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE, scheduledExecutorService) .build(); return HttpClientDependencies.builder() .clientConfiguration(clientConfiguration) .build(); } private static RequestExecutionContext createExecutionContext() { return RequestExecutionContext.builder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(ExecutionContext.builder() .executionAttributes(new ExecutionAttributes()) .metricCollector(NoOpMetricCollector.create()) .build()) .build(); } private static SdkHttpFullRequest createHttpRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("https") .host("amazon.com") .build(); } private void mockChildResponse(Response<Object> response) throws Exception { CompletableFuture<Response<Object>> result = CompletableFuture.completedFuture(response); when(mockChildPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))).thenReturn(result); } private void mockChildResponse(Exception error) throws Exception { CompletableFuture<Response<Object>> errorResult = CompletableFutureUtils.failedFuture(error); when(mockChildPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))).thenReturn(errorResult); } private void mockChildResponse(Error error) throws Exception { CompletableFuture<Response<Object>> errorResult = CompletableFutureUtils.failedFuture(error); when(mockChildPipeline.execute(any(SdkHttpFullRequest.class), any(RequestExecutionContext.class))).thenReturn(errorResult); } }
1,696
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/SigningStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.TIME_OFFSET; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import static software.amazon.awssdk.core.metrics.CoreMetric.SIGNING_DURATION; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; 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.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class SigningStageTest { private static final int TEST_TIME_OFFSET = 17; private static final SignerProperty<String> SIGNER_PROPERTY = SignerProperty.create(SigningStageTest.class, "key"); @Mock private Identity identity; @Mock private HttpSigner<Identity> httpSigner; @Mock private Signer oldSigner; @Mock MetricCollector metricCollector; @Captor private ArgumentCaptor<SignRequest<? extends Identity>> signRequestCaptor; private HttpClientDependencies httpClientDependencies; private SigningStage stage; @Before public void setup() { httpClientDependencies = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder().build()) .build(); // when tests update TimeOffset to non-zero value, it also sets SdkGlobalTime.setGlobalTimeOffset, // so explicitly setting this to default value before each test. httpClientDependencies.updateTimeOffset(0); stage = new SigningStage(httpClientDependencies); } @Test public void execute_selectedAuthScheme_nullSigner_doesSraSign() throws Exception { // Set up a scheme with a signer property SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.sign(ArgumentMatchers.<SignRequest<? extends Identity>>any())) .thenReturn(SignedRequest.builder() .request(signedRequest) .build()); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).usingRecursiveComparison().isEqualTo(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).sign(signRequestCaptor.capture()); SignRequest<? extends Identity> signRequest = signRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedAuthScheme_nullSigner_timeOffsetSet_doesSraSignAndAdjustTheSigningClock() throws Exception { // Set up a scheme with a signer property SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, null); // Setup the timeoffset to test that the clock is setup properly. httpClientDependencies.updateTimeOffset(TEST_TIME_OFFSET); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.sign(ArgumentMatchers.<SignRequest<? extends Identity>>any())) .thenReturn(SignedRequest.builder() .request(signedRequest) .build()); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).usingRecursiveComparison().isEqualTo(signedRequest); // Assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // Assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).sign(signRequestCaptor.capture()); SignRequest<? extends Identity> signRequest = signRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); // Assert that the signing clock is setup properly assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now().minusSeconds(17) , within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedAuthScheme_nullSigner_doesSraSignAndDoesNotOverrideAuthSchemeOptionClock() throws Exception { // Set up a scheme with a signer property and the signing clock set Clock clock = testClock(); SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") // The auth scheme option includes the signing clock property .putSignerProperty(HttpSigner.SIGNING_CLOCK, clock) .build()); RequestExecutionContext context = createContext(selectedAuthScheme, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.sign(ArgumentMatchers.<SignRequest<? extends Identity>>any())) .thenReturn(SignedRequest.builder() .request(signedRequest) .build()); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).usingRecursiveComparison().isEqualTo(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).sign(signRequestCaptor.capture()); SignRequest<? extends Identity> signRequest = signRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); // assert that the signing stage does not override the auth-option provided clock. assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isSameAs(clock); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedNoAuthAuthScheme_nullSigner_doesSraSign() throws Exception { // Set up a scheme with smithy.api#noAuth SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("smithy.api#noAuth") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.sign(ArgumentMatchers.<SignRequest<? extends Identity>>any())) .thenReturn(SignedRequest.builder() .request(signedRequest) .build()); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).usingRecursiveComparison().isEqualTo(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).sign(signRequestCaptor.capture()); SignRequest<? extends Identity> signRequest = signRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isNull(); // Assert that the time offset set was zero assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_nullSelectedAuthScheme_signer_doesPreSraSign() throws Exception { RequestExecutionContext context = createContext(null, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_nullSigner_skipsSigning() throws Exception { RequestExecutionContext context = createContext(null, null); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context); assertThat(result).isSameAs(request); // assert that interceptor context is updated with result, which is same as request. // To ensure this asserts the logic in the SigningStage to update the InterceptorContext before the signing logic, // the request is not set in the InterceptorContext in createContext() assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(request); verifyNoInteractions(metricCollector); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_signer_usesTimeOffset() throws Exception { httpClientDependencies.updateTimeOffset(100); RequestExecutionContext context = createContext(null, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 100))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_selectedAuthScheme_signer_doesPreSraSign() throws Exception { // Set up a scheme SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder().schemeId("my.auth#myAuth").build()); RequestExecutionContext context = createContext(selectedAuthScheme, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } private RequestExecutionContext createContext(SelectedAuthScheme<Identity> selectedAuthScheme, Signer oldSigner) { SdkRequest sdkRequest = ValidSdkObjects.sdkRequest(); InterceptorContext interceptorContext = InterceptorContext.builder() .request(sdkRequest) // Normally, this would be set, but there is logic to update the InterceptorContext before and // after signing, so keeping it not set here, so that logic can be asserted in tests. // .httpRequest(request) .build(); ExecutionAttributes.Builder executionAttributes = ExecutionAttributes.builder() .put(SELECTED_AUTH_SCHEME, selectedAuthScheme); if (selectedAuthScheme != null) { // Doesn't matter that it is empty, just needs to non-null, which implies SRA path. executionAttributes.put(SdkInternalExecutionAttribute.AUTH_SCHEMES, new HashMap<>()); } ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(executionAttributes.build()) .interceptorContext(interceptorContext) .signer(oldSigner) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .executionContext(executionContext) .originalRequest(sdkRequest) .build(); context.attemptMetricCollector(metricCollector); return context; } public static Clock testClock() { return new Clock() { @Override public ZoneId getZone() { throw new UnsupportedOperationException(); } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { return Instant.now(); } }; } }
1,697
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/pipeline/stages/AsyncSigningStageTest.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.core.internal.http.pipeline.stages; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.TIME_OFFSET; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import static software.amazon.awssdk.core.metrics.CoreMetric.SIGNING_DURATION; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.http.HttpClientDependencies; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.signer.AsyncRequestBodySigner; import software.amazon.awssdk.core.signer.AsyncSigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; 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.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class AsyncSigningStageTest { private static final int TEST_TIME_OFFSET = 17; private static final SignerProperty<String> SIGNER_PROPERTY = SignerProperty.create(AsyncSigningStageTest.class, "key"); @Mock private Identity identity; @Mock private HttpSigner<Identity> httpSigner; @Mock private Signer oldSigner; @Mock MetricCollector metricCollector; @Captor private ArgumentCaptor<SignRequest<? extends Identity>> signRequestCaptor; @Captor private ArgumentCaptor<AsyncSignRequest<? extends Identity>> asyncSignRequestCaptor; private HttpClientDependencies httpClientDependencies; private AsyncSigningStage stage; @Before public void setup() { httpClientDependencies = HttpClientDependencies.builder() .clientConfiguration(SdkClientConfiguration.builder().build()) .build(); // when tests update TimeOffset to non-zero value, it also sets SdkGlobalTime.setGlobalTimeOffset, // so explicitly setting this to default value before each test. httpClientDependencies.updateTimeOffset(0); stage = new AsyncSigningStage(httpClientDependencies); } @Test public void execute_selectedAuthScheme_nullSigner_doesSraSign() throws Exception { // Set up a scheme with a signer property SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.sign(ArgumentMatchers.<SignRequest<? extends Identity>>any())) .thenReturn(SignedRequest.builder() .request(signedRequest) .build()); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).usingRecursiveComparison().isEqualTo(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).sign(signRequestCaptor.capture()); SignRequest<? extends Identity> signRequest = signRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); // Assert that the time offset set was zero assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedAuthScheme_nullSigner_timeOffsetSet_doesSraSignAndAdjustTheSigningClock() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); // Set up a scheme with a signer property SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, asyncPayload, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); Publisher<ByteBuffer> signedPayload = AsyncRequestBody.fromString("signed async request body"); when(httpSigner.signAsync(ArgumentMatchers.<AsyncSignRequest<? extends Identity>>any())) .thenReturn( CompletableFuture.completedFuture(AsyncSignedRequest.builder() .request(signedRequest) .payload(signedPayload) .build())); // Setup the timeoffset to test that the clock is setup properly. httpClientDependencies.updateTimeOffset(TEST_TIME_OFFSET); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).signAsync(asyncSignRequestCaptor.capture()); AsyncSignRequest<? extends Identity> signRequest = asyncSignRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); // Assert that the signing clock is setup properly assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now().minusSeconds(17) , within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedAuthScheme_nullSigner_doesSraSignAndDoesNotOverrideAuthSchemeOptionClock() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); // Set up a scheme with a signer property and the signing clock set Clock clock = SigningStageTest.testClock(); SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") // The auth scheme option includes the signing clock property .putSignerProperty(HttpSigner.SIGNING_CLOCK, clock) .build()); RequestExecutionContext context = createContext(selectedAuthScheme, asyncPayload, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); when(httpSigner.signAsync(ArgumentMatchers.<AsyncSignRequest<? extends Identity>>any())) .thenReturn( CompletableFuture.completedFuture(AsyncSignedRequest.builder() .request(signedRequest) .build())); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).signAsync(asyncSignRequestCaptor.capture()); AsyncSignRequest<? extends Identity> signRequest = asyncSignRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); // Assert that the time offset set was zero assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that the signing stage does not override the auth-option provided clock. assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isSameAs(clock); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedAuthScheme_asyncRequestBody_doesSraSignAsync() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); // Set up a scheme with a signer property SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("my.auth#myAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, asyncPayload, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); Publisher<ByteBuffer> signedPayload = AsyncRequestBody.fromString("signed async request body"); when(httpSigner.signAsync(ArgumentMatchers.<AsyncSignRequest<? extends Identity>>any())) .thenReturn( CompletableFuture.completedFuture(AsyncSignedRequest.builder() .request(signedRequest) .payload(signedPayload) .build())); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).isSameAs(signedRequest); // assert that contexts are updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); assertThat(context.executionContext().interceptorContext().asyncRequestBody().get()).isSameAs(signedPayload); assertThat(context.requestProvider()).isSameAs(signedPayload); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).signAsync(asyncSignRequestCaptor.capture()); AsyncSignRequest<? extends Identity> signRequest = asyncSignRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.payload().get()).isSameAs(asyncPayload); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); // Assert that the time offset set was zero assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_selectedNoAuthAuthScheme_nullSigner_doesSraSign() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); // Set up a scheme with smithy.api#noAuth SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder() .schemeId("smithy.api#noAuth") .putSignerProperty(SIGNER_PROPERTY, "value") .build()); RequestExecutionContext context = createContext(selectedAuthScheme, asyncPayload, null); SdkHttpRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); Publisher<ByteBuffer> signedPayload = AsyncRequestBody.fromString("signed async request body"); when(httpSigner.signAsync(ArgumentMatchers.<AsyncSignRequest<? extends Identity>>any())) .thenReturn( CompletableFuture.completedFuture(AsyncSignedRequest.builder() .request(signedRequest) .payload(signedPayload) .build())); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).isSameAs(signedRequest); // assert that contexts are updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); assertThat(context.executionContext().interceptorContext().asyncRequestBody().get()).isSameAs(signedPayload); assertThat(context.requestProvider()).isSameAs(signedPayload); // assert that the input to the signer is as expected, including that signer properties are set verify(httpSigner).signAsync(asyncSignRequestCaptor.capture()); AsyncSignRequest<? extends Identity> signRequest = asyncSignRequestCaptor.getValue(); assertThat(signRequest.identity()).isSameAs(identity); assertThat(signRequest.request()).isSameAs(request); assertThat(signRequest.property(SIGNER_PROPERTY)).isEqualTo("value"); assertThat(signRequest.payload().get()).isSameAs(asyncPayload); // Assert that the time offset set was zero assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK)).isNotNull(); assertThat(signRequest.property(HttpSigner.SIGNING_CLOCK).instant()) .isCloseTo(Instant.now(), within(10, ChronoUnit.MILLIS)); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(oldSigner); } @Test public void execute_nullSelectedAuthScheme_signer_doesPreSraSign() throws Exception { RequestExecutionContext context = createContext(null, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_AsyncRequestBodySigner_doesPreSraSignAsyncRequestBody() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); AsyncRequestBody signedPayload = AsyncRequestBody.fromString("signed async request body"); TestAsyncRequestBodySigner asyncRequestBodySigner = mock(TestAsyncRequestBodySigner.class); RequestExecutionContext context = createContext(null, asyncPayload, asyncRequestBodySigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(asyncRequestBodySigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))).thenReturn(signedRequest); when(asyncRequestBodySigner.signAsyncRequestBody(signedRequest, asyncPayload, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))) .thenReturn(signedPayload); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(result).isSameAs(signedRequest); // assert that contexts are updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // Note: pre SRA code did not set this, so commenting it out, as compared to the SRA test. // assertThat(context.executionContext().interceptorContext().asyncRequestBody().get()).isSameAs(signedPayload); assertThat(context.requestProvider()).isSameAs(signedPayload); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_AsyncSigner_doesPreSraSignAsync() throws Exception { AsyncRequestBody asyncPayload = AsyncRequestBody.fromString("async request body"); TestAsyncSigner asyncSigner = mock(TestAsyncSigner.class); RequestExecutionContext context = createContext(null, asyncPayload, asyncSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(asyncSigner.sign(request, asyncPayload, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))) .thenReturn(CompletableFuture.completedFuture(signedRequest)); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(result).isSameAs(signedRequest); // assert that contexts are updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // Note: compared to SRA code, AsyncSigner use case did not set asyncPayload on the context or the // interceptorContext. // So commenting the interceptorContext assertion, as compared to the SRA test. // assertThat(context.executionContext().interceptorContext().asyncRequestBody().get()).isSameAs(asyncPayload); // And the context.requestProvider is the input asyncPayload itself, there is no different signedPayload as compared to // the SRA test. assertThat(context.requestProvider()).isSameAs(asyncPayload); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_nullSigner_skipsSigning() throws Exception { RequestExecutionContext context = createContext(null, null); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(result).isSameAs(request); // assert that interceptor context is updated with result, which is same as request. // To ensure this asserts the logic in the SigningStage to update the InterceptorContext before the signing logic, // the request is not set in the InterceptorContext in createContext() assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(request); verifyNoInteractions(metricCollector); verifyNoInteractions(httpSigner); } @Test public void execute_nullSelectedAuthScheme_signer_usesTimeOffset() throws Exception { httpClientDependencies.updateTimeOffset(100); RequestExecutionContext context = createContext(null, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 100))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(context.executionAttributes().getAttribute(TIME_OFFSET)) .isEqualTo(httpClientDependencies.timeOffset()); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } @Test public void execute_selectedAuthScheme_signer_doesPreSraSign() throws Exception { // Set up a scheme SelectedAuthScheme<Identity> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(identity), httpSigner, AuthSchemeOption.builder().schemeId("my.auth#myAuth").build()); RequestExecutionContext context = createContext(selectedAuthScheme, oldSigner); SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); SdkHttpFullRequest signedRequest = ValidSdkObjects.sdkHttpFullRequest().build(); // Creating a copy because original executionAttributes may be directly mutated by SigningStage, e.g., timeOffset when(oldSigner.sign(request, context.executionAttributes().copy().putAttribute(TIME_OFFSET, 0))).thenReturn(signedRequest); SdkHttpFullRequest result = stage.execute(request, context).join(); assertThat(result).isSameAs(signedRequest); // assert that interceptor context is updated with result assertThat(context.executionContext().interceptorContext().httpRequest()).isSameAs(result); // assert that metrics are collected verify(metricCollector).reportMetric(eq(SIGNING_DURATION), any()); verifyNoInteractions(httpSigner); } private RequestExecutionContext createContext(SelectedAuthScheme<Identity> selectedAuthScheme, Signer oldSigner) { return createContext(selectedAuthScheme, null, oldSigner); } private RequestExecutionContext createContext(SelectedAuthScheme<Identity> selectedAuthScheme, AsyncRequestBody requestProvider, Signer oldSigner) { SdkRequest sdkRequest = ValidSdkObjects.sdkRequest(); InterceptorContext interceptorContext = InterceptorContext.builder() .request(sdkRequest) // Normally, this would be set, but there is logic to update the InterceptorContext before and // after signing, so keeping it not set here, so that logic can be asserted in tests. // .httpRequest(request) .build(); ExecutionAttributes.Builder executionAttributes = ExecutionAttributes.builder() .put(SELECTED_AUTH_SCHEME, selectedAuthScheme); if (selectedAuthScheme != null) { // Doesn't matter that it is empty, just needs to non-null, which implies SRA path. executionAttributes.put(SdkInternalExecutionAttribute.AUTH_SCHEMES, new HashMap<>()); } ExecutionContext executionContext = ExecutionContext.builder() .executionAttributes(executionAttributes.build()) .interceptorContext(interceptorContext) .signer(oldSigner) .build(); RequestExecutionContext context = RequestExecutionContext.builder() .executionContext(executionContext) .originalRequest(sdkRequest) .requestProvider(requestProvider) .build(); context.attemptMetricCollector(metricCollector); return context; } private interface TestAsyncRequestBodySigner extends Signer, AsyncRequestBodySigner { } private interface TestAsyncSigner extends Signer, AsyncSigner { } }
1,698
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/DummyResponseHandler.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.core.internal.http.response; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * ResponseHandler implementation to return an empty response */ public class DummyResponseHandler implements HttpResponseHandler<SdkResponse> { private boolean needsConnectionLeftOpen = false; @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return VoidSdkResponse.builder().build(); } @Override public boolean needsConnectionLeftOpen() { return needsConnectionLeftOpen; } /** * Enable streaming * * @return Object for method chaining */ public DummyResponseHandler leaveConnectionOpen() { this.needsConnectionLeftOpen = true; return this; } }
1,699