index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/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,900
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,901
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,902
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,903
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,904
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,905
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,906
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,907
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,908
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,909
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,910
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,911
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,912
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,913
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,914
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,915
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,916
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,917
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,918
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,919
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,920
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,921
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,922
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,923
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,924
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,925
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,926
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,927
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,928
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,929
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,930
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,931
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,932
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,933
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,934
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,935
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,936
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,937
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,938
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,939
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,940
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,941
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,942
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,943
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,944
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,945
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,946
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,947
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,948
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,949
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,950
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,951
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,952
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,953
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,954
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,955
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,956
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,957
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,958
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,959
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,960
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,961
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,962
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,963
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,964
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,965
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,966
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,967
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,968
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,969
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,970
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,971
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,972
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/ErrorDuringUnmarshallingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class ErrorDuringUnmarshallingResponseHandler extends NullResponseHandler { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { throw new RuntimeException("Unable to unmarshall response"); } }
1,973
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/UnresponsiveResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http.SdkHttpFullResponse; /** * Error Response Handler implementation that hangs forever */ public class UnresponsiveResponseHandler implements HttpResponseHandler<SdkResponse> { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { Thread.sleep(Long.MAX_VALUE); return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,974
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/NullErrorResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class NullErrorResponseHandler implements HttpResponseHandler<SdkServiceException> { @Override public SdkServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return SdkServiceException.builder().build(); } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,975
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/EmptySdkResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; public class EmptySdkResponseHandler implements HttpResponseHandler<SdkResponse> { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return VoidSdkResponse.builder().build(); } @Override public boolean needsConnectionLeftOpen() { return true; } }
1,976
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/UnresponsiveErrorResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Response Handler implementation that hangs forever */ public class UnresponsiveErrorResponseHandler implements HttpResponseHandler<SdkServiceException> { @Override public SdkServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { Thread.sleep(Long.MAX_VALUE); return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,977
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/NullResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class NullResponseHandler implements HttpResponseHandler<SdkResponse> { public static void assertIsUnmarshallingException(SdkClientException e) { assertThat(e.getCause(), instanceOf(RuntimeException.class)); RuntimeException re = (RuntimeException) e.getCause(); assertThat(re.getMessage(), containsString("Unable to unmarshall response")); } @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,978
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/timers/HttpClientApiCallTimeoutTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.noOpSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; 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.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class HttpClientApiCallTimeoutTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonSyncHttpClient httpClient; @Before public void setup() { httpClient = testClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallTimeout(API_CALL_TIMEOUT) .build(); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); assertThatThrownBy(() -> requestBuilder().execute(combinedSyncResponseHandler( superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()), null))) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); assertThatThrownBy(() -> httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedSyncResponseHandler(noOpSyncResponseHandler(), superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())))) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallTimeoutException.class); } private AmazonSyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,979
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/timers/AsyncHttpClientApiCallTimeoutTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.combinedAsyncResponseHandler; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.noOpResponseHandler; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testAsyncClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; 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.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class AsyncHttpClientApiCallTimeoutTests { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonAsyncHttpClient httpClient; @Before public void setup() { httpClient = testAsyncClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallTimeout(API_CALL_TIMEOUT) .build(); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); CompletableFuture future = httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedAsyncResponseHandler(noOpResponseHandler(), superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()))); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void errorResponse_SlowAfterErrorRequestHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain( Collections.singletonList(new SlowExecutionInterceptor().onExecutionFailureWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT))); SdkHttpFullRequest request = generateRequest(); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(request) .build(); ExecutionContext executionContext = ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); CompletableFuture future = httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .request(request) .executionContext(executionContext) .execute(combinedAsyncResponseHandler(noOpResponseHandler(), noOpResponseHandler(SdkServiceException.builder().build()))); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowBeforeRequestRequestHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); CompletableFuture future = requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpResponseHandler()); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); CompletableFuture future = requestBuilder().execute(superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void slowApiAttempt_ThrowsApiCallAttemptTimeoutException() { httpClient = testAsyncClientBuilder() .apiCallTimeout(API_CALL_TIMEOUT) .apiCallAttemptTimeout(Duration.ofMillis(1)) .build(); stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}").withFixedDelay(1_000))); CompletableFuture future = requestBuilder().execute(noOpResponseHandler()); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallAttemptTimeoutException.class); } private AmazonAsyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,980
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/timers/HttpClientApiCallAttemptTimeoutTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.noOpSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; 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.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class HttpClientApiCallAttemptTimeoutTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonSyncHttpClient httpClient; @Before public void setup() { httpClient = testClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallAttemptTimeout(API_CALL_TIMEOUT) .build(); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); assertThatThrownBy(() -> requestBuilder().execute(combinedSyncResponseHandler( superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()), null))) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); assertThatThrownBy(() -> httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedSyncResponseHandler(null, superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())))) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallAttemptTimeoutException.class); } private AmazonSyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,981
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/timers/SyncTimeoutTaskTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; public class SyncTimeoutTaskTest { private static final ExecutorService EXEC = Executors.newSingleThreadExecutor(); @AfterAll public static void teardown() { EXEC.shutdown(); } @Test public void taskInProgress_hasExecutedReturnsTrue() throws InterruptedException { Thread mockThread = mock(Thread.class); SyncTimeoutTask task = new SyncTimeoutTask(mockThread); CountDownLatch latch = new CountDownLatch(1); task.abortable(() -> { try { latch.countDown(); Thread.sleep(1000); } catch (InterruptedException e) { } }); EXEC.submit(task); latch.await(); assertThat(task.hasExecuted()).isTrue(); } @Test public void taskInProgress_cancelCalled_abortableIsNotInterrupted() throws InterruptedException { Thread mockThread = mock(Thread.class); SyncTimeoutTask task = new SyncTimeoutTask(mockThread); AtomicBoolean interrupted = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(1); task.abortable(() -> { try { latch.countDown(); Thread.sleep(1000); } catch (InterruptedException e) { interrupted.set(true); } }); EXEC.submit(task); latch.await(); task.cancel(); assertThat(interrupted.get()).isFalse(); } }
1,982
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/timers/TimeoutTestConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import java.time.Duration; /** * Constants relevant for request timeout and client execution timeout tests */ public class TimeoutTestConstants { public static final int TEST_TIMEOUT = 25 * 1000; public static final Duration API_CALL_TIMEOUT = Duration.ofSeconds(1); public static final int SLOW_REQUEST_HANDLER_TIMEOUT = 2; /** * ScheduledThreadPoolExecutor isn't exact and can be delayed occasionally. For tests where we * are asserting that a certain timeout comes first (i.e. SocketTimeout is triggered before * Request timeout or Request Timeout is triggered before Client execution timeout) then we need * to add a comfortable margin to ensure tests don't fail. */ public static final int PRECISION_MULTIPLIER = 5; }
1,983
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/timers/ClientExecutionAndRequestTimerTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.timers; import static org.junit.Assert.assertEquals; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import java.net.URI; import java.util.Collections; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; 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.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.ErrorDuringUnmarshallingResponseHandler; import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.metrics.MetricCollector; /** * Useful asserts and utilities for verifying behavior or the client execution timeout and request * timeout features */ public class ClientExecutionAndRequestTimerTestUtils { /** * Can take a little bit for ScheduledThreadPoolExecutor to update it's internal state */ private static final int WAIT_BEFORE_ASSERT_ON_EXECUTOR = 500; /** * Waits until a little after the thread pools keep alive time and then asserts that all thre * * @param timerExecutor Executor used by timer implementation */ public static void assertCoreThreadsShutDownAfterBeingIdle(ScheduledThreadPoolExecutor timerExecutor) { try { Thread.sleep(timerExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS) + 1000); } catch (InterruptedException ignored) { // Ignored. } assertEquals(0, timerExecutor.getPoolSize()); } /** * If the request completes successfully then the timer task should be canceled and should be * removed from the thread pool to prevent build up of canceled tasks * * @param timerExecutor Executor used by timer implementation */ public static void assertCanceledTasksRemoved(ScheduledThreadPoolExecutor timerExecutor) { waitBeforeAssertOnExecutor(); assertEquals(0, timerExecutor.getQueue().size()); } /** * Asserts the timer never went off (I.E. no timeout was exceeded and no timer task was * executed) * * @param timerExecutor Executor used by timer implementation */ public static void assertTimerNeverTriggered(ScheduledThreadPoolExecutor timerExecutor) { assertNumberOfTasksTriggered(timerExecutor, 0); } private static void assertNumberOfTasksTriggered(ScheduledThreadPoolExecutor timerExecutor, int expectedNumberOfTasks) { waitBeforeAssertOnExecutor(); assertEquals(expectedNumberOfTasks, timerExecutor.getCompletedTaskCount()); } public static SdkHttpFullRequest.Builder createMockGetRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("http://localhost:0")) .method(SdkHttpMethod.GET); } /** * Execute the request with a dummy response handler and error response handler */ public static void execute(AmazonSyncHttpClient httpClient, SdkHttpFullRequest request) { httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(new ErrorDuringUnmarshallingResponseHandler(), new NullErrorResponseHandler())); } public static ExecutionContext executionContext(SdkHttpFullRequest request) { InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(request) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(new ExecutionInterceptorChain(Collections.emptyList())) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } private static void waitBeforeAssertOnExecutor() { try { Thread.sleep(WAIT_BEFORE_ASSERT_ON_EXECUTOR); } catch (InterruptedException ignored) { // Ignored. } } public static void interruptCurrentThreadAfterDelay(final long delay) { final Thread currentThread = Thread.currentThread(); new Thread() { public void run() { try { Thread.sleep(delay); currentThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }
1,984
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/async/CombinedResponseAsyncHttpResponseHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpFullResponse; class CombinedResponseAsyncHttpResponseHandlerTest { private CombinedResponseAsyncHttpResponseHandler<Void> responseHandler; private TransformingAsyncResponseHandler<Void> successResponseHandler; private TransformingAsyncResponseHandler<SdkClientException> errorResponseHandler; @BeforeEach public void setup() { successResponseHandler = Mockito.mock(TransformingAsyncResponseHandler.class); errorResponseHandler = Mockito.mock(TransformingAsyncResponseHandler.class); responseHandler = new CombinedResponseAsyncHttpResponseHandler<>(successResponseHandler, errorResponseHandler); } @Test void onStream_invokedWithoutPrepare_shouldThrowException() { assertThatThrownBy(() -> responseHandler.onStream(publisher())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("onStream() invoked"); } @Test void onHeaders_invokedWithoutPrepare_shouldThrowException() { assertThatThrownBy(() -> responseHandler.onHeaders(SdkHttpFullResponse.builder().build())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("onHeaders() invoked"); } @Test void onStream_invokedWithoutOnHeaders_shouldThrowException() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); responseHandler.prepare(); assertThatThrownBy(() -> responseHandler.onStream(publisher())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("headersFuture is still not completed when onStream()"); } @Test void onStream_HeadersFutureCompleteSuccessfully_shouldNotThrowException() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); responseHandler.prepare(); responseHandler.onError(new RuntimeException("error")); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onStream(publisher); verify(successResponseHandler, times(0)).onStream(publisher); verify(errorResponseHandler, times(0)).onStream(publisher); } @Test void successResponse_shouldCompleteHeaderFuture() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Response<Void>> future = responseHandler.prepare(); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onHeaders(sdkHttpFullResponse); responseHandler.onStream(publisher); verify(successResponseHandler).prepare(); verify(successResponseHandler).onStream(publisher); assertThat(future).isDone(); assertThat(future.join().httpResponse()).isEqualTo(sdkHttpFullResponse); } @Test void errorResponse_shouldCompleteHeaderFuture() { when(errorResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Response<Void>> future = responseHandler.prepare(); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(400) .build(); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onHeaders(sdkHttpFullResponse); responseHandler.onStream(publisher); verify(errorResponseHandler).prepare(); verify(errorResponseHandler).onStream(publisher); assertThat(future).isDone(); assertThat(future.join().httpResponse()).isEqualTo(sdkHttpFullResponse); } private static Flowable<ByteBuffer> publisher() { return Flowable.just(ByteBuffer.wrap("string".getBytes(StandardCharsets.UTF_8))); } }
1,985
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/async/SimpleRequestProviderTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * TCK verification test for {@link SimpleHttpContentPublisher}. */ public class SimpleRequestProviderTckTest extends PublisherVerification<ByteBuffer> { private static final byte[] CONTENT = new byte[4906]; public SimpleRequestProviderTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long l) { return new SimpleHttpContentPublisher(makeFullRequest()); } @Override public long maxElementsFromPublisher() { // SimpleRequestProvider is a one shot publisher return 1; } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } private static SdkHttpFullRequest makeFullRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("https://aws.amazon.com")) .method(SdkHttpMethod.PUT) .contentStreamProvider(() -> new ByteArrayInputStream(CONTENT)) .build(); } }
1,986
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/loader/CachingSdkHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.loader; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; 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.http.SdkHttpService; @RunWith(MockitoJUnitRunner.class) public class CachingSdkHttpServiceProviderTest { @Mock private SdkHttpServiceProvider<SdkHttpService> delegate; private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = new CachingSdkHttpServiceProvider<>(delegate); } @Test(expected = NullPointerException.class) public void nullDelegate_ThrowsException() { new CachingSdkHttpServiceProvider<>(null); } @Test public void delegateReturnsEmptyOptional_DelegateCalledOnce() { when(delegate.loadService()).thenReturn(Optional.empty()); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); } @Test public void delegateReturnsNonEmptyOptional_DelegateCalledOne() { when(delegate.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); } }
1,987
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/loader/SdkHttpServiceProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.loader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.Test; import software.amazon.awssdk.http.SdkHttpService; public class SdkHttpServiceProviderChainTest { @Test(expected = NullPointerException.class) public void nullProviders_ThrowsException() { new SdkHttpServiceProviderChain<>(null); } @Test(expected = IllegalArgumentException.class) public void emptyProviders_ThrowsException() { new SdkHttpServiceProviderChain<>(); } @Test public void allProvidersReturnEmpty_ReturnsEmptyOptional() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.empty()); when(delegateTwo.loadService()).thenReturn(Optional.empty()); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isEmpty(); } @Test public void firstProviderReturnsNonEmpty_DoesNotCallSecondProvider() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isPresent(); verify(delegateTwo, never()).loadService(); } }
1,988
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/loader/SystemPropertyHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.loader; import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpService; public class SystemPropertyHttpServiceProviderTest { private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = SystemPropertyHttpServiceProvider.syncProvider(); } @After public void tearDown() { System.clearProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property()); } @Test public void systemPropertyNotSet_ReturnsEmptyOptional() { assertThat(provider.loadService()).isEmpty(); } @Test(expected = SdkClientException.class) public void systemPropertySetToInvalidClassName_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), "com.invalid.ClassName"); provider.loadService(); } @Test(expected = SdkClientException.class) public void systemPropertySetToNonServiceClass_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), getClass().getName()); provider.loadService(); } @Test(expected = SdkClientException.class) public void systemPropertySetToServiceClassWithNoDefaultCtor_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), HttpServiceWithNoDefaultCtor.class.getName()); provider.loadService(); } @Test public void systemPropertySetToValidClass_ReturnsFulfulledOptional() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), MockHttpService.class.getName()); assertThat(provider.loadService()).isPresent(); } public static final class MockHttpService implements SdkHttpService { @Override public SdkHttpClient.Builder createHttpClientBuilder() { return null; } } public static final class HttpServiceWithNoDefaultCtor implements SdkHttpService { HttpServiceWithNoDefaultCtor(String foo) { } @Override public SdkHttpClient.Builder createHttpClientBuilder() { return null; } } }
1,989
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/loader/ClasspathSdkHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.loader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Iterator; 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.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpService; @RunWith(MockitoJUnitRunner.class) public class ClasspathSdkHttpServiceProviderTest { @Mock private SdkServiceLoader serviceLoader; private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = new ClasspathSdkHttpServiceProvider<>(serviceLoader, SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL, SdkHttpService.class); } @Test public void noImplementationsFound_ReturnsEmptyOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf()); assertThat(provider.loadService()).isEmpty(); } @Test public void oneImplementationsFound_ReturnsFulfilledOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class))); assertThat(provider.loadService()).isPresent(); } @Test(expected = SdkClientException.class) public void multipleImplementationsFound_ThrowsException() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class), mock(SdkHttpService.class))); provider.loadService(); } @SafeVarargs private final <T> Iterator<T> iteratorOf(T... items) { return Arrays.asList(items).iterator(); } }
1,990
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/request/SlowExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.request; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * Implementation of {@link ExecutionInterceptor} with configurable wait times */ public class SlowExecutionInterceptor implements ExecutionInterceptor { private int beforeTransmissionWait; private int afterTransmissionWait; private int onExecutionFailureWait; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { wait(beforeTransmissionWait); } @Override public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { wait(afterTransmissionWait); } @Override public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { wait(onExecutionFailureWait); } private void wait(int secondsToWait) { if (secondsToWait > 0) { try { Thread.sleep(secondsToWait * 1000); } catch (InterruptedException e) { // Be a good citizen an re-interrupt the current thread Thread.currentThread().interrupt(); } } } public SlowExecutionInterceptor beforeTransmissionWaitInSeconds(int beforeTransmissionWait) { this.beforeTransmissionWait = beforeTransmissionWait; return this; } public SlowExecutionInterceptor afterTransmissionWaitInSeconds(int afterTransmissionWait) { this.afterTransmissionWait = afterTransmissionWait; return this; } public SlowExecutionInterceptor onExecutionFailureWaitInSeconds(int onExecutionFailureWait) { this.onExecutionFailureWait = onExecutionFailureWait; return this; } }
1,991
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/compression/GzipCompressorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.compression; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.Is.is; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import org.junit.Test; public class GzipCompressorTest { private static final Compressor gzipCompressor = new GzipCompressor(); private static final String COMPRESSABLE_STRING = "RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest"; @Test public void compressedData_decompressesCorrectly() throws IOException { byte[] originalData = COMPRESSABLE_STRING.getBytes(StandardCharsets.UTF_8); byte[] compressedData = gzipCompressor.compress(originalData); int uncompressedSize = originalData.length; int compressedSize = compressedData.length; assertThat(compressedSize, lessThan(uncompressedSize)); 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(); assertThat(decompressedData, is(originalData)); } }
1,992
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/sync/FileContentStreamProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.sync; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * Tests for {@link FileContentStreamProvider}. */ public class FileContentStreamProviderTest { private static FileSystem testFs; private static Path testFile; @BeforeAll public static void setup() throws IOException { testFs = Jimfs.newFileSystem("FileContentStreamProviderTest"); testFile = testFs.getPath("test_file.dat"); try (OutputStream os = Files.newOutputStream(testFile)) { os.write("test".getBytes(StandardCharsets.UTF_8)); } } @AfterAll public static void teardown() throws IOException { testFs.close(); } @Test public void newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); } }
1,993
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/checksum/CrtBasedChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.checksum; import static org.assertj.core.api.Assertions.assertThat; import java.util.zip.Checksum; import org.junit.Test; import software.amazon.awssdk.core.internal.checksums.factory.CrtBasedChecksumProvider; public class CrtBasedChecksumTest { @Test public void doNot_loadCrc32CrtPathClassesInCore() { Checksum checksum = CrtBasedChecksumProvider.createCrc32(); assertThat(checksum).isNull(); } @Test public void doNot_loadCrc32_C_CrtPathClassesInCore() { Checksum checksum = CrtBasedChecksumProvider.createCrc32C(); assertThat(checksum).isNull(); } }
1,994
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/waiters/WaiterOverrideConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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; public class WaiterOverrideConfigurationTest { @Test public void valuesProvided_shouldReturnOptionalValues() { WaiterOverrideConfiguration configuration = WaiterOverrideConfiguration.builder() .maxAttempts(10) .backoffStrategy(BackoffStrategy.none()) .waitTimeout(Duration.ofSeconds(1)) .build(); assertThat(configuration.backoffStrategy()).contains(BackoffStrategy.none()); assertThat(configuration.maxAttempts()).contains(10); assertThat(configuration.waitTimeout()).contains(Duration.ofSeconds(1)); } @Test public void valuesNotProvided_shouldReturnEmptyOptionalValues() { WaiterOverrideConfiguration configuration = WaiterOverrideConfiguration.builder().build(); assertThat(configuration.backoffStrategy()).isEmpty(); assertThat(configuration.maxAttempts()).isEmpty(); assertThat(configuration.waitTimeout()).isEmpty(); } @Test public void nonPositiveMaxWaitTime_shouldThrowException() { assertThatThrownBy(() -> WaiterOverrideConfiguration.builder() .waitTimeout(Duration.ZERO) .build()).hasMessageContaining("must be positive"); } @Test public void nonPositiveMaxAttempts_shouldThrowException() { assertThatThrownBy(() -> WaiterOverrideConfiguration.builder() .maxAttempts(-10) .build()).hasMessageContaining("must be positive"); } @Test public void toBuilder_shouldGenerateSameBuilder() { WaiterOverrideConfiguration overrideConfiguration = WaiterOverrideConfiguration.builder() .waitTimeout(Duration.ofSeconds(2)) .maxAttempts(10) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1))) .build(); WaiterOverrideConfiguration config = overrideConfiguration.toBuilder().build(); assertThat(overrideConfiguration).isEqualTo(config); assertThat(overrideConfiguration.hashCode()).isEqualTo(config.hashCode()); } }
1,995
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/waiters/WaiterAcceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.Predicate; import org.testng.annotations.Test; public class WaiterAcceptorTest { private static final String STRING_TO_MATCH = "foobar"; private static final Predicate<String> STRING_PREDICATE = s -> s.equals(STRING_TO_MATCH); private static final Predicate<Throwable> EXCEPTION_PREDICATE = s -> s.getMessage().equals(STRING_TO_MATCH); @Test public void successOnResponseAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .successOnResponseAcceptor(STRING_PREDICATE); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.SUCCESS); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnResponseAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnResponseAcceptorWithMsg() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE, "wrong response"); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).contains("wrong response"); } @Test public void errorOnResponseAcceptor_nullMsg_shouldThrowException() { assertThatThrownBy(() -> WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE, null)).hasMessageContaining("message must not be null"); } @Test public void errorOnResponseAcceptor_nullPredicate_shouldThrowException() { assertThatThrownBy(() -> WaiterAcceptor .errorOnResponseAcceptor(null)).hasMessageContaining("responsePredicate must not be null"); } @Test public void successOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .successOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.SUCCESS); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void retryOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .retryOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.RETRY); assertThat(objectWaiterAcceptor.message()).isEmpty(); } }
1,996
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/waiters/AsyncWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.BiFunction; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.utils.CompletableFutureUtils; public class AsyncWaiterTest extends BaseWaiterTest { @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ReturnResponseResource(count)).join(); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ThrowExceptionResource(count)).join(); } @Test public void matchException_exceptionIsWrapped_shouldReturnUnwrappedException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnWrappedExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).isExactlyInstanceOf(RuntimeException.class); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void missingScheduledExecutor_shouldThrowException() { assertThatThrownBy(() -> AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .build() .runAsync(() -> null)) .hasMessageContaining("executorService"); } @Test public void concurrentWaiterOperations_shouldBeThreadSafe() { AsyncWaiter<String> waiter = AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .scheduledExecutorService(executorService) .build(); CompletableFuture<WaiterResponse<String>> waiterResponse1 = waiter.runAsync(new ReturnResponseResource(2)); CompletableFuture<WaiterResponse<String>> waiterResponse2 = waiter.runAsync(new ReturnResponseResource(3)); CompletableFuture.allOf(waiterResponse1, waiterResponse2).join(); assertThat(waiterResponse1.join().attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse2.join().attemptsExecuted()).isEqualTo(3); } @Test public void requestOverrideConfig_shouldTakePrecedence() { AsyncWaiter<String> waiter = AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .scheduledExecutorService(executorService) .build(); assertThatThrownBy(() -> waiter.runAsync(new ReturnResponseResource(2), o -> o.maxAttempts(1)) .join()).hasMessageContaining("exceeded the max retry attempts: 1"); } private BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnWrappedExceptionWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ThrowCompletionExceptionResource(count)).join(); } private static final class ReturnResponseResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ReturnResponseResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFuture.completedFuture(NON_SUCCESS_STATE_MESSAGE); } return CompletableFuture.completedFuture(SUCCESS_STATE_MESSAGE); } } private static final class ThrowExceptionResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ThrowExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFutureUtils.failedFuture(new RuntimeException(NON_SUCCESS_STATE_MESSAGE)); } return CompletableFutureUtils.failedFuture(new RuntimeException(SUCCESS_STATE_MESSAGE)); } } private static final class ThrowCompletionExceptionResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ThrowCompletionExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFutureUtils.failedFuture(new CompletionException(new RuntimeException(NON_SUCCESS_STATE_MESSAGE))); } return CompletableFutureUtils.failedFuture(new CompletionException(new RuntimeException(SUCCESS_STATE_MESSAGE))); } } }
1,997
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/waiters/BaseWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiFunction; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public abstract class BaseWaiterTest { static final String SUCCESS_STATE_MESSAGE = "helloworld"; static final String NON_SUCCESS_STATE_MESSAGE = "other"; static ScheduledExecutorService executorService; @BeforeAll public static void setUp() { executorService = Executors.newScheduledThreadPool(2); } @AfterAll public static void tearDown() { executorService.shutdown(); } @Test public void successOnResponse_matchSuccessInFirstAttempt_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().response()).contains(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnResponse_matchError_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.errorOnResponseAcceptor(s -> s.equals(NON_SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnResponse_matchSuccessInSecondAttempt_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(2, waiterConfig); assertThat(response.matched().response()).contains(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(2); } @Test public void successOnResponse_noMatch_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("No acceptor was matched for the response"); } @Test public void successOnResponse_noMatchExceedsMaxAttempts_shouldRetryThreeTimesAndThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(4, waiterConfig)).hasMessageContaining("max retry attempts"); } @Test public void successOnResponse_multipleMatchingAcceptors_firstTakesPrecedence() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.errorOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(1, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnResponse_fixedBackOffStrategy() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); long start = System.currentTimeMillis(); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(5, waiterConfig); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(4000L, 5000L); assertThat(response.attemptsExecuted()).isEqualTo(5); } @Test public void successOnResponse_waitTimeout() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5) .waitTimeout(Duration.ofSeconds(2)) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); long start = System.currentTimeMillis(); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(5, waiterConfig)).hasMessageContaining("has exceeded the max wait time"); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(1000L, 3000L); } @Test public void successOnException_matchSuccessInFirstAttempt_shouldReturnException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnException_hasRetryAcceptorMatchSuccessInSecondAttempt_shouldReturnException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnExceptionAcceptor(s -> s.getMessage().contains(NON_SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(2, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(2); } @Test public void successOnException_unexpectedExceptionAndNoRetryAcceptor_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnExceptionWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("did not match"); } @Test public void successOnException_matchError_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.errorOnExceptionAcceptor(s -> s.getMessage().contains(NON_SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnExceptionWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnException_multipleMatchingAcceptors_firstTakesPrecedence() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.errorOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnException_fixedBackOffStrategy() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.retryOnExceptionAcceptor(s -> s.getMessage().equals(NON_SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().equals(SUCCESS_STATE_MESSAGE))); long start = System.currentTimeMillis(); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(5, waiterConfig); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(4000L, 5000L); assertThat(response.attemptsExecuted()).isEqualTo(5); } public abstract BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation(); public abstract BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation(); class TestWaiterConfiguration implements WaiterBuilder<String, TestWaiterConfiguration> { private List<WaiterAcceptor<? super String>> waiterAcceptors = new ArrayList<>(); private WaiterOverrideConfiguration overrideConfiguration; /** * @return */ public List<WaiterAcceptor<? super String>> getWaiterAcceptors() { return waiterAcceptors; } /** * @return */ public WaiterOverrideConfiguration getPollingStrategy() { return overrideConfiguration; } @Override public TestWaiterConfiguration acceptors(List<WaiterAcceptor<? super String>> waiterAcceptors) { this.waiterAcceptors = waiterAcceptors; return this; } @Override public TestWaiterConfiguration addAcceptor(WaiterAcceptor<? super String> waiterAcceptor) { waiterAcceptors.add(waiterAcceptor); return this; } @Override public TestWaiterConfiguration overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration) { this.overrideConfiguration = overrideConfiguration; return this; } } }
1,998
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/waiters/WaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public class WaiterTest extends BaseWaiterTest { private static final String SUCCESS_STATE_MESSAGE = "helloworld"; private static final String NON_SUCCESS_STATE_MESSAGE = "other"; private BackoffStrategy backoffStrategy; @BeforeEach public void setup() { backoffStrategy = FixedDelayBackoffStrategy.create(Duration.ofMillis(10)); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation() { return (count, waiterConfiguration) -> Waiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()).build().run(new ReturnResponseResource(count)); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation() { return (count, waiterConfiguration) -> Waiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()).build().run(new ThrowExceptionResource(count)); } @Test public void concurrentWaiterOperations_shouldBeThreadSafe() { Waiter<String> waiter = Waiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .build(); CompletableFuture<WaiterResponse<String>> waiterResponse1 = CompletableFuture.supplyAsync(() -> waiter.run(new ReturnResponseResource(2)), executorService); CompletableFuture<WaiterResponse<String>> waiterResponse2 = CompletableFuture.supplyAsync(() -> waiter.run(new ReturnResponseResource(3)), executorService); CompletableFuture.allOf(waiterResponse1, waiterResponse2).join(); assertThat(waiterResponse1.join().attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse2.join().attemptsExecuted()).isEqualTo(3); } @Test public void requestOverrideConfig_shouldTakePrecedence() { Waiter<String> waiter = Waiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .build(); assertThatThrownBy(() -> waiter.run(new ReturnResponseResource(2), o -> o.maxAttempts(1))) .hasMessageContaining("exceeded the max retry attempts: 1"); } private static final class ReturnResponseResource implements Supplier<String> { private final int successAttemptIndex; private int count; public ReturnResponseResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public String get() { if (++count < successAttemptIndex) { return NON_SUCCESS_STATE_MESSAGE; } return SUCCESS_STATE_MESSAGE; } } private static final class ThrowExceptionResource implements Supplier<String> { private final int successAttemptIndex; private int count; public ThrowExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public String get() { if (++count < successAttemptIndex) { throw new RuntimeException(NON_SUCCESS_STATE_MESSAGE); } throw new RuntimeException(SUCCESS_STATE_MESSAGE); } public int count() { return count; } } }
1,999