method2testcases
stringlengths
118
6.63k
### Question: CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); }### Answer: @Test public void firstIfPresent_NullList_ReturnsNull() { List<String> list = null; assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } @Test public void firstIfPresent_EmptyList_ReturnsNull() { List<String> list = Collections.emptyList(); assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } @Test public void firstIfPresent_SingleElementList_ReturnsOnlyElement() { assertThat(CollectionUtils.firstIfPresent(singletonList("foo"))).isEqualTo("foo"); } @Test public void firstIfPresent_MultipleElementList_ReturnsFirstElement() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList("foo", "bar", "baz"))).isEqualTo("foo"); } @Test public void firstIfPresent_FirstElementNull_ReturnsNull() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList(null, "bar", "baz"))).isNull(); }
### Question: AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer: @Test public void modifyAsyncHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, getExecutionAttributes()); assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingPublisher.class); } @Test public void modifyAsyncHttpResponseContent_getObjectRequest_responseDoesNotContainChecksum_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); SdkHttpResponse sdkHttpResponse = SdkHttpResponse.builder() .putHeader(CONTENT_LENGTH_HEADER, "100") .build(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); } @Test public void modifyAsyncHttpResponseContent_nonGetObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); sdkHttpResponse.toBuilder().clearHeaders(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); }
### Question: ToString { public static String create(String className) { return className + "()"; } private ToString(String className); static String create(String className); static ToString builder(String className); ToString add(String fieldName, Object field); String build(); }### Answer: @Test public void createIsCorrect() { assertThat(ToString.create("Foo")).isEqualTo("Foo()"); }
### Question: ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } private ImmutableMap(Map<K, V> map); static Builder<K, V> builder(); static ImmutableMap<K, V> of(K k0, V v0); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4); boolean containsKey(Object key); boolean containsValue(Object value); Set<Entry<K, V>> entrySet(); V get(Object key); boolean isEmpty(); Set<K> keySet(); int size(); Collection<V> values(); void clear(); V put(K key, V value); void putAll(Map<? extends K, ? extends V> map); V remove(Object key); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testErrorOnDuplicateKeys() { try { Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>() .put(1, "one") .put(1, "two") .build(); fail("IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } catch (Exception e) { fail("IllegalArgumentException expected."); } }
### Question: ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix); ThreadFactoryBuilder daemonThreads(Boolean daemonThreads); ThreadFactory build(); }### Answer: @Test public void poolNumberWrapsAround() { for (int i = 0; i < 9_9999; i++) { new ThreadFactoryBuilder().build(); } Thread threadBeforeWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadBeforeWrap.getName()).isEqualTo("aws-java-sdk-9999-0"); Thread threadAfterWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadAfterWrap.getName()).isEqualTo("aws-java-sdk-0-0"); }
### Question: MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace, Set<SdkMetric<String>> dimensions, Set<MetricCategory> metricCategories, MetricLevel metricLevel, Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); static final int MAX_METRIC_DATA_PER_REQUEST; static final int MAX_VALUES_PER_REQUEST; }### Answer: @Test public void maximumRequestsIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests(); assertThat(requests).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); }); requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); assertThat(requests.get(0).metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); assertThat(requests.get(1).metricData()).hasSize(1); } @Test public void maximumMetricValuesIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST).getRequests(); assertThat(requests).hasSize(1); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); validateValuesCount(requests.get(1), 1); }
### Question: UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } UploadMetricsTasks(MetricCollectionAggregator collectionAggregator, MetricUploader uploader, int maximumRequestsPerFlush); @Override CompletableFuture<?> call(); }### Answer: @Test public void extraTasksAboveMaximumAreDropped() { List<PutMetricDataRequest> requests = Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build()); Mockito.when(aggregator.getRequests()).thenReturn(requests); task.call(); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); Mockito.verify(uploader).upload(captor.capture()); List<PutMetricDataRequest> uploadedRequests = captor.getValue(); assertThat(uploadedRequests).hasSize(2); assertThat(uploadedRequests).containsOnlyElementsOf(requests); }
### Question: MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); }### Answer: @Test public void uploadSuccessIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompleted(); } @Test public void uploadFailureIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).completeExceptionally(new Throwable()); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompletedExceptionally(); }
### Question: MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); }### Answer: @Test public void closeFalseDoesNotCloseClient() { uploader.close(false); Mockito.verify(client, never()).close(); } @Test public void closeTrueClosesClient() { uploader.close(true); Mockito.verify(client, times(1)).close(); }
### Question: CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); }### Answer: @Test public void namespaceSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.namespace("namespace").build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } assertThat(getPutMetricCall().namespace()).isEqualTo("namespace"); } @Test public void maximumCallsPerPublishSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.maximumCallsPerUpload(1) .detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY) .build()) { for (int i = 0; i < MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } assertThat(getPutMetricCalls()).hasSize(1); } @Test public void detailedMetricsSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY).build()) { for (int i = 0; i < 10; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 10); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } PutMetricDataRequest call = getPutMetricCall(); MetricDatum concurrencyMetric = getDatum(call, HttpMetric.MAX_CONCURRENCY); MetricDatum availableConcurrency = getDatum(call, HttpMetric.AVAILABLE_CONCURRENCY); assertThat(concurrencyMetric.values()).isEmpty(); assertThat(concurrencyMetric.counts()).isEmpty(); assertThat(concurrencyMetric.statisticValues()).isNotNull(); assertThat(availableConcurrency.values()).isNotEmpty(); assertThat(availableConcurrency.counts()).isNotEmpty(); assertThat(availableConcurrency.statisticValues()).isNull(); }
### Question: SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); }### Answer: @Test public void propertiesNotSet_returnsNull() { assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void propertiesSet_createsKeyManager() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), Paths.get("does", "not", "exist").toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), "invalid"); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), "not correct password"); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { assertThat(PROVIDER.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } }
### Question: FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); }### Answer: @Test(expected = NullPointerException.class) public void storePathNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(null, CLIENT_STORE_TYPE, STORE_PASSWORD); } @Test(expected = NullPointerException.class) public void storeTypeNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, null, STORE_PASSWORD); } @Test(expected = IllegalArgumentException.class) public void storeTypeEmpty_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, "", STORE_PASSWORD); } @Test public void passwordNotGiven_doesNotThrowValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, null); }
### Question: IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata, Map<String, OperationModel> operations, Map<String, ShapeModel> shapes, CustomizationConfig customizationConfig); IntermediateModel( Metadata metadata, Map<String, OperationModel> operations, Map<String, ShapeModel> shapes, CustomizationConfig customizationConfig, OperationModel endpointOperation, Map<String, AuthorizerModel> customAuthorizers, Map<String, PaginatorDefinition> paginators, NamingStrategy namingStrategy, Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); }### Answer: @Test public void cannotFindShapeWhenNoShapesExist() { ServiceMetadata metadata = new ServiceMetadata(); metadata.setProtocol(Protocol.REST_JSON.getValue()); metadata.setServiceId("empty-service"); metadata.setSignatureVersion("V4"); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(new ServiceModel(metadata, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("AnyShape", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name AnyShape does not exist in the intermediate model."); } @Test public void getShapeByNameAndC2jNameVerifiesC2JName() { final File modelFile = new File(IntermediateModelTest.class .getResource("../../poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("PingResponse", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name PingResponse does not exist in the intermediate model."); }
### Question: DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel, CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); }### Answer: @Test public void canConvertStringsWithNonAlphasToClassNames() { String anInvalidClassName = "a phrase-With_other.delimiters"; assertThat(strat.getJavaClassName(anInvalidClassName)).isEqualTo("APhraseWithOtherDelimiters"); } @Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("_MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("__MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoublePeriods() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("..MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleDashes() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("--MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_DoubleUnderscoresInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My__Class"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_DoublePeriodsInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My..Class"); assertThat(javaClassName).isEqualTo("MyClass"); } @Test public void getJavaClassName_ReturnsSanitizedName_DoubleDashesInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My--Class"); assertThat(javaClassName).isEqualTo("MyClass"); }
### Question: DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } DefaultNamingStrategy(ServiceModel serviceModel, CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); }### Answer: @Test public void canConvertAuthorizerStartingWithNumber() { String anInvalidClassName = "35-authorizer-implementation"; assertThat(strat.getAuthorizerClassName(anInvalidClassName)).isEqualTo("I35AuthorizerImplementation"); }
### Question: AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer: @Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); } @Test public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(INVALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE) .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); }
### Question: DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel, CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); }### Answer: @Test public void getServiceName_Uses_ServiceId() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn("Foo"); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); assertThat(strat.getServiceName()).isEqualTo("Foo"); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsNull() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(null); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsEmpty() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(""); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdHasWhiteSpace() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(" "); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); }
### Question: DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel, CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); }### Answer: @Test public void getSdkFieldFieldName_SingleWord() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("foo"))) .isEqualTo("FOO_FIELD"); } @Test public void getSdkFieldFieldName_CamalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("fooBar"))) .isEqualTo("FOO_BAR_FIELD"); } @Test public void getSdkFieldFieldName_PascalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("FooBar"))) .isEqualTo("FOO_BAR_FIELD"); }
### Question: PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }### Answer: @Test public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(PutObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-continue"); } @Test public void modifyHttpRequest_doesNotSetExpect_whenSdkRequestIsNotPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(GetObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).isNotPresent(); }
### Question: DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); }### Answer: @Test public void strip_html_tags_null_or_empty_input_returns_empty_string() { Assert.assertThat(DocumentationUtils.stripHtmlTags(null), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags(""), Matchers .isEmptyString()); } @Test public void html_tags_at_start_of_string_are_removed() { Assert.assertEquals("foo", DocumentationUtils.stripHtmlTags ("<bar>foo</bar>")); } @Test public void empty_html_tags_at_start_are_removed() { Assert.assertThat(DocumentationUtils.stripHtmlTags("<p></p>"), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags("<p/>"), Matchers .isEmptyString()); }
### Question: Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } private Utils(); static boolean isScalar(Shape shape); static boolean isStructure(Shape shape); static boolean isListShape(Shape shape); static boolean isMapShape(Shape shape); static boolean isEnumShape(Shape shape); static boolean isExceptionShape(Shape shape); static boolean isOrContainsEnumShape(Shape shape, Map<String, Shape> allShapes); static boolean isOrContainsEnum(MemberModel member); static boolean isListWithEnumShape(MemberModel member); static boolean isMapWithEnumShape(MemberModel member); static boolean isMapKeyWithEnumShape(MapModel mapModel); static boolean isMapValueWithEnumShape(MapModel mapModel); static String unCapitalize(String name); static String capitalize(String name); static String removeLeading(String str, String toRemove); static String removeTrailing(String str, String toRemove); static String getFileNamePrefix(ServiceModel serviceModel); static String directoryToPackage(String directoryPath); static String packageToDirectory(String packageName); static String getDefaultEndpointWithoutHttpProtocol(String endpoint); static File createDirectory(String path); static void createDirectory(File dir); static File createFile(String dir, String fileName); static boolean isNullOrEmpty(String str); static void closeQuietly(Closeable closeable); static InputStream getRequiredResourceAsStream(Class<?> clzz, String location); static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findMemberShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static List<ShapeModel> findShapesByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation); }### Answer: @Test public void testUnCapitalize() { capitalizedToUncapitalized.forEach((capitalized,unCapitalized) -> assertThat(Utils.unCapitalize(capitalized), is(equalTo(unCapitalized)))); }
### Question: UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); }### Answer: @Test public void unusedImportsAreRemoved() throws Exception { String content = loadFileContents(FILE_WITH_UNUSED_IMPORTS_JAVA); String expected = loadFileContents(FILE_WITHOUT_UNUSED_IMPORTS_JAVA); String result = sut.apply(content); assertThat(result, equalToIgnoringWhiteSpace(expected)); } @Test public void nonJavaContentIsIgnored() throws Exception { String jsonContent = "{ \"SomeKey\": 4, \"ADict\": { \"SubKey\": \"Subvalue\" } }"; String result = sut.apply(jsonContent); assertThat(result, equalTo(jsonContent)); }
### Question: ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); }### Answer: @Test public void responseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(model); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(model); assertThat(responseSpec, generatesTo(responseSpec.className().simpleName().toLowerCase() + ".java")); } @Test public void customResponseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(modelWithCustomizedResponseMetadata); assertThat(spec, generatesTo("./customresponsemetadata/" + spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(modelWithCustomizedResponseMetadata); assertThat(responseSpec, generatesTo("./customresponsemetadata/" + responseSpec.className().simpleName().toLowerCase() + ".java")); }
### Question: AwsServiceBaseResponseSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkResponseBaseClassName()); } AwsServiceBaseResponseSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); }### Answer: @Test public void testGeneration() { AwsServiceBaseResponseSpec spec = new AwsServiceBaseResponseSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); }
### Question: AwsServiceBaseRequestSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkRequestBaseClassName()); } AwsServiceBaseRequestSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); }### Answer: @Test public void testGeneration() { AwsServiceBaseRequestSpec spec = new AwsServiceBaseRequestSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); }
### Question: PoetCollectors { public static Collector<CodeBlock, ?, CodeBlock> toCodeBlock() { return Collector.of(CodeBlock::builder, CodeBlock.Builder::add, PoetCollectors::parallelNotSupported, CodeBlock.Builder::build); } private PoetCollectors(); static Collector<CodeBlock, ?, CodeBlock> toCodeBlock(); static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter); }### Answer: @Test public void emptyCollectIsEmptyCodeBlock() { CodeBlock result = Stream.<CodeBlock>of().collect(PoetCollectors.toCodeBlock()); assertThat(result).isEqualTo(CodeBlock.builder().build()); } @Test public void codeBlocksJoined() { CodeBlock a = CodeBlock.of("a"); CodeBlock b = CodeBlock.of("b"); CodeBlock ab = CodeBlock.builder().add(a).add(b).build(); CodeBlock result = Stream.of(a, b).collect(PoetCollectors.toCodeBlock()); assertThat(result).isEqualTo(ab); }
### Question: PoetCollectors { public static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter) { return Collector.of(() -> new CodeBlockJoiner(delimiter), CodeBlockJoiner::add, PoetCollectors::parallelNotSupported, CodeBlockJoiner::join); } private PoetCollectors(); static Collector<CodeBlock, ?, CodeBlock> toCodeBlock(); static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter); }### Answer: @Test public void emptyDelimitedCollectIsEmptyCodeBlock() { CodeBlock result = Stream.<CodeBlock>of().collect(PoetCollectors.toDelimitedCodeBlock(",")); assertThat(result).isEqualTo(CodeBlock.builder().build()); } @Test public void delimitedCodeBlocksJoined() { CodeBlock a = CodeBlock.of("a"); CodeBlock b = CodeBlock.of("b"); CodeBlock delimeter = CodeBlock.of(","); CodeBlock ab = CodeBlock.builder().add(a).add(delimeter).add(b).build(); CodeBlock result = Stream.of(a, b).collect(PoetCollectors.toDelimitedCodeBlock(",")); assertThat(result).isEqualTo(ab); }
### Question: EndpointDiscoveryCacheLoaderGenerator implements ClassSpec { private MethodSpec create() { return MethodSpec.methodBuilder("create") .addModifiers(STATIC, PUBLIC) .returns(className()) .addParameter(poetExtensions.getClientClass(model.getMetadata().getSyncInterface()), CLIENT_FIELD) .addStatement("return new $T($L)", className(), CLIENT_FIELD) .build(); } EndpointDiscoveryCacheLoaderGenerator(GeneratorTaskParams generatorTaskParams); @Override TypeSpec poetSpec(); @Override ClassName className(); }### Answer: @Test public void syncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/"); EndpointDiscoveryCacheLoaderGenerator cacheLoader = new EndpointDiscoveryCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-sync-cache-loader.java")); } @Test public void asyncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/"); EndpointDiscoveryAsyncCacheLoaderGenerator cacheLoader = new EndpointDiscoveryAsyncCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-async-cache-loader.java")); }
### Question: Crc32Validation { public static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse) { if (!httpResponse.content().isPresent()) { return httpResponse; } return httpResponse.toBuilder().content( process(calculateCrc32FromCompressedData, httpResponse, httpResponse.content().get())).build(); } private Crc32Validation(); static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse); }### Answer: @Test public void adapt_CalculateCrcFromCompressed_WrapsWithCrc32ThenGzip() throws IOException { try (InputStream content = getClass().getResourceAsStream("/resources/compressed_json_body.gz")) { SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("Content-Encoding", "gzip") .putHeader("x-amz-crc32", "1234") .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = Crc32Validation.validate(true, httpResponse); InputStream in = getField(adapted.content().get(), "in"); assertThat(in).isInstanceOf((GZIPInputStream.class)); } }
### Question: IdempotentUtils { @Deprecated @SdkProtectedApi public static String resolveString(String token) { return token != null ? token : generator.get(); } private IdempotentUtils(); @Deprecated @SdkProtectedApi static String resolveString(String token); @SdkProtectedApi static Supplier<String> getGenerator(); @SdkTestInternalApi static void setGenerator(Supplier<String> newGenerator); }### Answer: @Test public void resolveString_returns_givenString_when_nonnullString_is_passed() { String idempotencyToken = "120c7d4a-e982-4323-a53e-28989a0a9f26"; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_emptyString_when_emptyString_is_passed() { String idempotencyToken = ""; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_newUniqueToken_when_nullString_is_passed() { assertNotNull(IdempotentUtils.resolveString(null)); }
### Question: GetBucketPolicyInterceptor implements ExecutionInterceptor { @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (INTERCEPTOR_CONTEXT_PREDICATE.test(context)) { String policy = context.responseBody() .map(r -> invokeSafely(() -> IoUtils.toUtf8String(r))) .orElse(null); if (policy != null) { String xml = XML_ENVELOPE_PREFIX + policy + XML_ENVELOPE_SUFFIX; return Optional.of(AbortableInputStream.create(new StringInputStream(xml))); } } return context.responseBody(); } @Override Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes); }### Answer: @Test public void getBucketPolicy_shouldModifyResponseContent() { GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder() .statusCode(200) .build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isNotEqualTo(context.responseBody()); } @Test public void nonGetBucketPolicyResponse_ShouldNotModifyResponse() { GetObjectRequest request = GetObjectRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(200).build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isEqualTo(context.responseBody()); } @Test public void errorResponseShouldNotModifyResponse() { GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(404).build()); Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes()); assertThat(inputStream).isEqualTo(context.responseBody()); }
### Question: DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public boolean equals(Object o) { return impl.equals(o); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void equals_emptyList() { assertThat(INSTANCE.equals(new LinkedList<>())).isTrue(); }
### Question: DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public int hashCode() { return impl.hashCode(); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hashCode_sameAsEmptyList() { assertThat(INSTANCE.hashCode()).isEqualTo(new LinkedList<>().hashCode()); assertThat(INSTANCE.hashCode()).isEqualTo(1); }
### Question: DefaultSdkAutoConstructList implements SdkAutoConstructList<T> { @Override public String toString() { return impl.toString(); } private DefaultSdkAutoConstructList(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructList<T> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override T get(int index); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<T> listIterator(); @Override ListIterator<T> listIterator(int index); @Override List<T> subList(int fromIndex, int toIndex); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void toString_emptyList() { assertThat(INSTANCE.toString()).isEqualTo("[]"); }
### Question: DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public boolean equals(Object o) { return impl.equals(o); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void equal_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.equals(new HashMap<>())).isTrue(); }
### Question: DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public int hashCode() { return impl.hashCode(); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hashCode_sameAsEmptyMap() { assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(new HashMap<>().hashCode()); assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(0); }
### Question: DefaultSdkAutoConstructMap implements SdkAutoConstructMap<K, V> { @Override public String toString() { return impl.toString(); } private DefaultSdkAutoConstructMap(); @SuppressWarnings("unchecked") static DefaultSdkAutoConstructMap<K, V> getInstance(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V value); @Override V remove(Object key); @Override void putAll(Map<? extends K, ? extends V> m); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void toString_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.toString()).isEqualTo("{}"); }
### Question: PaginatorUtils { public static <T> boolean isOutputTokenAvailable(T outputToken) { if (outputToken == null) { return false; } if (outputToken instanceof String) { return !((String) outputToken).isEmpty(); } if (outputToken instanceof Map) { return !((Map) outputToken).isEmpty(); } if (outputToken instanceof Collection) { return !((Collection) outputToken).isEmpty(); } return true; } private PaginatorUtils(); static boolean isOutputTokenAvailable(T outputToken); }### Answer: @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())); }
### Question: RequestOverrideConfiguration { public Map<String, List<String>> headers() { return headers; } protected RequestOverrideConfiguration(Builder<?> builder); Map<String, List<String>> headers(); Map<String, List<String>> rawQueryParameters(); List<ApiName> apiNames(); Optional<Duration> apiCallTimeout(); Optional<Duration> apiCallAttemptTimeout(); Optional<Signer> signer(); List<MetricPublisher> metricPublishers(); @Override boolean equals(Object o); @Override int hashCode(); abstract Builder<? extends Builder> toBuilder(); }### Answer: @Test public void addSameItemAfterSetCollection_shouldOverride() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .headers(map) .putHeader(HEADER, "blah") .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("blah"); } @Test public void shouldGuaranteeImmutability() { List<String> headerValues = new ArrayList<>(); headerValues.add("bar"); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", headerValues); SdkRequestOverrideConfiguration.Builder configurationBuilder = SdkRequestOverrideConfiguration.builder().headers(headers); headerValues.add("test"); headers.put("new header", Collections.singletonList("new value")); assertThat(configurationBuilder.headers().size()).isEqualTo(1); assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar"); }
### Question: RequestOverrideConfiguration { public List<MetricPublisher> metricPublishers() { return metricPublishers; } protected RequestOverrideConfiguration(Builder<?> builder); Map<String, List<String>> headers(); Map<String, List<String>> rawQueryParameters(); List<ApiName> apiNames(); Optional<Duration> apiCallTimeout(); Optional<Duration> apiCallAttemptTimeout(); Optional<Signer> signer(); List<MetricPublisher> metricPublishers(); @Override boolean equals(Object o); @Override int hashCode(); abstract Builder<? extends Builder> toBuilder(); }### Answer: @Test public void metricPublishers_createsCopy() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); List<MetricPublisher> toModify = new ArrayList<>(publishers); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .metricPublishers(toModify) .build(); toModify.clear(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_maintainsAllAdded() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); publishers.forEach(builder::addMetricPublisher); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void metricPublishers_overwritesPreviouslyAdded() { MetricPublisher firstAdded = mock(MetricPublisher.class); List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.addMetricPublisher(firstAdded); builder.metricPublishers(publishers); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_listPreviouslyAdded_appendedToList() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); MetricPublisher thirdAdded = mock(MetricPublisher.class); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.metricPublishers(publishers); builder.addMetricPublisher(thirdAdded); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded); }
### Question: AsyncStreamingRequestMarshaller extends AbstractStreamingRequestMarshaller<T> { @Override public SdkHttpFullRequest marshall(T in) { SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder(); addHeaders(marshalled, asyncRequestBody.contentLength(), requiresLength, transferEncoding, useHttp2); return marshalled.build(); } private AsyncStreamingRequestMarshaller(Builder builder); static Builder builder(); @Override SdkHttpFullRequest marshall(T in); }### Answer: @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(); }
### Question: RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public int totalRequests() { return this.retriesAttempted + 1; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); }### Answer: @Test public void totalRequests_IsOneMoreThanRetriesAttempted() { assertEquals(4, RetryPolicyContexts.withRetriesAttempted(3).totalRequests()); }
### Question: RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public Integer httpStatusCode() { return this.httpStatusCode; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); }### Answer: @Test public void nullHttpStatusCodeAllowed() { assertNull(RetryPolicyContexts.withStatusCode(null).httpStatusCode()); }
### Question: RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> { public SdkException exception() { return this.exception; } private RetryPolicyContext(Builder builder); static Builder builder(); SdkRequest originalRequest(); SdkHttpFullRequest request(); SdkException exception(); ExecutionAttributes executionAttributes(); int retriesAttempted(); int totalRequests(); Integer httpStatusCode(); @Override Builder toBuilder(); }### Answer: @Test public void nullExceptionAllowed() { assertNull(RetryPolicyContexts.withException(null).exception()); }
### Question: DefaultWaiterResponse implements WaiterResponse<T> { public static <T> Builder<T> builder() { return new Builder<>(); } private DefaultWaiterResponse(Builder<T> builder); static Builder<T> builder(); @Override ResponseOrException<T> matched(); @Override int attemptsExecuted(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void missingAttemptsExecuted_shouldThrowException() { assertThatThrownBy(() -> DefaultWaiterResponse.<String>builder().response("foobar") .build()).hasMessageContaining("attemptsExecuted"); }
### Question: S3ArnUtils { public static S3AccessPointResource parseS3AccessPointArn(Arn arn) { return S3AccessPointResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .accessPointName(arn.resource().resource()) .build(); } private S3ArnUtils(); static S3AccessPointResource parseS3AccessPointArn(Arn arn); static IntermediateOutpostResource parseOutpostArn(Arn arn); }### Answer: @Test public void parseS3AccessPointArn_shouldParseCorrectly() { S3AccessPointResource s3AccessPointResource = S3ArnUtils.parseS3AccessPointArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:accesspoint-name") .build()); assertThat(s3AccessPointResource.accessPointName(), is("accesspoint-name")); assertThat(s3AccessPointResource.accountId(), is(Optional.of("123456789012"))); assertThat(s3AccessPointResource.partition(), is(Optional.of("aws"))); assertThat(s3AccessPointResource.region(), is(Optional.of("us-east-1"))); assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString())); }
### Question: MakeHttpRequestStage implements RequestPipeline<SdkHttpFullRequest, Pair<SdkHttpFullRequest, SdkHttpFullResponse>> { public Pair<SdkHttpFullRequest, SdkHttpFullResponse> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { InterruptMonitor.checkInterrupted(); HttpExecuteResponse executeResponse = executeHttpRequest(request, context); SdkHttpFullResponse httpResponse = (SdkHttpFullResponse) executeResponse.httpResponse(); return Pair.of(request, httpResponse.toBuilder().content(executeResponse.responseBody().orElse(null)).build()); } MakeHttpRequestStage(HttpClientDependencies dependencies); Pair<SdkHttpFullRequest, SdkHttpFullResponse> execute(SdkHttpFullRequest request, RequestExecutionContext context); }### Answer: @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) { } finally { ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(mockClient).prepareRequest(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } }
### Question: MakeAsyncHttpRequestStage implements RequestPipeline<CompletableFuture<SdkHttpFullRequest>, CompletableFuture<Response<OutputT>>> { @Override public CompletableFuture<Response<OutputT>> execute(CompletableFuture<SdkHttpFullRequest> requestFuture, RequestExecutionContext context) { CompletableFuture<Response<OutputT>> toReturn = new CompletableFuture<>(); CompletableFutureUtils.forwardExceptionTo(requestFuture, toReturn); CompletableFutureUtils.forwardExceptionTo(toReturn, requestFuture); requestFuture.thenAccept(request -> { try { CompletableFuture<Response<OutputT>> executeFuture = executeHttpRequest(request, context); executeFuture.whenComplete((r, t) -> { if (t != null) { toReturn.completeExceptionally(t); } else { toReturn.complete(r); } }); CompletableFutureUtils.forwardExceptionTo(toReturn, executeFuture); } catch (Throwable t) { toReturn.completeExceptionally(t); } }); return toReturn; } MakeAsyncHttpRequestStage(TransformingAsyncResponseHandler<Response<OutputT>> responseHandler, HttpClientDependencies dependencies); @Override CompletableFuture<Response<OutputT>> execute(CompletableFuture<SdkHttpFullRequest> requestFuture, RequestExecutionContext context); }### Answer: @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(); } finally { ArgumentCaptor<AsyncExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(mockCollector).createChild(eq("HttpClient")); verify(sdkAsyncHttpClient).execute(httpRequestCaptor.capture()); assertThat(httpRequestCaptor.getValue().metricCollector()).contains(childCollector); } }
### Question: ApiCallAttemptTimeoutTrackingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { long timeoutInMillis = resolveTimeoutInMillis(context.requestConfig()::apiCallAttemptTimeout, apiCallAttemptTimeout); TimeoutTracker timeoutTracker = timeSyncTaskIfNeeded(timeoutExecutor, timeoutInMillis, Thread.currentThread()); Response<OutputT> response; try { context.apiCallAttemptTimeoutTracker(timeoutTracker); response = wrapped.execute(request, context); } finally { timeoutTracker.cancel(); } if (timeoutTracker.hasExecuted()) { Thread.interrupted(); } return response; } catch (Exception e) { throw translatePipelineException(context, e); } } ApiCallAttemptTimeoutTrackingStage(HttpClientDependencies dependencies, RequestPipeline<SdkHttpFullRequest, Response<OutputT>> wrapped); @Override Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context); }### Answer: @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(); }
### Question: AsyncApiCallTimeoutTrackingStage implements RequestPipeline<SdkHttpFullRequest, CompletableFuture<OutputT>> { @Override public CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context) throws Exception { CompletableFuture<OutputT> future = new CompletableFuture<>(); long apiCallTimeoutInMillis = resolveTimeoutInMillis(() -> context.requestConfig().apiCallTimeout(), clientConfig.option(SdkClientOption.API_CALL_TIMEOUT)); Supplier<SdkClientException> exceptionSupplier = () -> ApiCallTimeoutException.create(apiCallTimeoutInMillis); TimeoutTracker timeoutTracker = timeAsyncTaskIfNeeded(future, scheduledExecutor, exceptionSupplier, apiCallTimeoutInMillis); context.apiCallTimeoutTracker(timeoutTracker); CompletableFuture<OutputT> executeFuture = requestPipeline.execute(input, context); executeFuture.whenComplete((r, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(r); } }); return CompletableFutureUtils.forwardExceptionTo(future, executeFuture); } AsyncApiCallTimeoutTrackingStage(HttpClientDependencies dependencies, RequestPipeline<SdkHttpFullRequest, CompletableFuture<OutputT>> requestPipeline); @Override CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context); }### Answer: @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)); }
### Question: ApiCallTimeoutTrackingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { return executeWithTimer(request, context); } catch (Exception e) { throw translatePipelineException(context, e); } } ApiCallTimeoutTrackingStage(HttpClientDependencies dependencies, RequestPipeline<SdkHttpFullRequest, Response<OutputT>> wrapped); @Override Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context); }### Answer: @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(); }
### Question: SystemPropertyHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { return implSetting .getStringValue() .map(this::createServiceFromProperty); } private SystemPropertyHttpServiceProvider(SystemSetting implSetting, Class<T> serviceClass); @Override Optional<T> loadService(); }### Answer: @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(); }
### Question: SdkHttpServiceProviderChain implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { return httpProviders.stream() .map(SdkHttpServiceProvider::loadService) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } @SafeVarargs SdkHttpServiceProviderChain(SdkHttpServiceProvider<T>... httpProviders); @Override Optional<T> loadService(); }### Answer: @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(); }
### Question: CachingSdkHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { if (factory == null) { synchronized (this) { if (factory == null) { this.factory = delegate.loadService(); } } } return factory; } CachingSdkHttpServiceProvider(SdkHttpServiceProvider<T> delegate); @Override Optional<T> loadService(); }### Answer: @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(); }
### Question: ClasspathSdkHttpServiceProvider implements SdkHttpServiceProvider<T> { @Override public Optional<T> loadService() { Iterator<T> httpServices = serviceLoader.loadServices(serviceClass); if (!httpServices.hasNext()) { return Optional.empty(); } T httpService = httpServices.next(); if (httpServices.hasNext()) { throw SdkClientException.builder().message( String.format( "Multiple HTTP implementations were found on the classpath. To avoid non-deterministic loading " + "implementations, please explicitly provide an HTTP client via the client builders, set the %s " + "system property with the FQCN of the HTTP service to use as the default, or remove all but one " + "HTTP implementation from the classpath", implSystemProperty.property())) .build(); } return Optional.of(httpService); } @SdkTestInternalApi ClasspathSdkHttpServiceProvider(SdkServiceLoader serviceLoader, SystemSetting implSystemProperty, Class<T> serviceClass); @Override Optional<T> loadService(); }### Answer: @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(); }
### Question: MetricUtils { public static <T> Pair<T, Duration> measureDuration(Supplier<T> c) { long start = System.nanoTime(); T result = c.get(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); }### Answer: @Test public void testMeasureDuration_returnsAccurateDurationInformation() { long testDurationNanos = Duration.ofMillis(1).toNanos(); Pair<Object, Duration> measuredExecute = MetricUtils.measureDuration(() -> { long start = System.nanoTime(); while (System.nanoTime() - start < testDurationNanos) { } return "foo"; }); assertThat(measuredExecute.right()).isGreaterThanOrEqualTo(Duration.ofNanos(testDurationNanos)); } @Test public void testMeasureDuration_returnsCallableReturnValue() { String result = "foo"; Pair<String, Duration> measuredExecute = MetricUtils.measureDuration(() -> result); assertThat(measuredExecute.left()).isEqualTo(result); } @Test public void testMeasureDuration_doesNotWrapException() { RuntimeException e = new RuntimeException("boom"); thrown.expect(RuntimeException.class); try { MetricUtils.measureDuration(() -> { throw e; }); } catch (RuntimeException caught) { assertThat(caught).isSameAs(e); throw caught; } }
### Question: MetricUtils { public static <T> Pair<T, Duration> measureDurationUnsafe(Callable<T> c) throws Exception { long start = System.nanoTime(); T result = c.call(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); }### Answer: @Test public void testMeasureDurationUnsafe_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; } }
### Question: MetricUtils { public static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse) { if (metricCollector != null && httpResponse != null) { metricCollector.reportMetric(HttpMetric.HTTP_STATUS_CODE, httpResponse.statusCode()); SdkHttpUtils.allMatchingHeadersFromCollection(httpResponse.headers(), X_AMZN_REQUEST_ID_HEADERS) .forEach(v -> metricCollector.reportMetric(CoreMetric.AWS_REQUEST_ID, v)); httpResponse.firstMatchingHeader(X_AMZ_ID_2_HEADER) .ifPresent(v -> metricCollector.reportMetric(CoreMetric.AWS_EXTENDED_REQUEST_ID, v)); } } private MetricUtils(); static Pair<T, Duration> measureDuration(Supplier<T> c); static Pair<T, Duration> measureDurationUnsafe(Callable<T> c); static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse); static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context); static MetricCollector createHttpMetricsCollector(RequestExecutionContext context); }### Answer: @Test public void testCollectHttpMetrics_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); }
### Question: Mimetype { public String getMimetype(Path path) { Validate.notNull(path, "path"); Path file = path.getFileName(); if (file != null) { return getMimetype(file.toString()); } return MIMETYPE_OCTET_STREAM; } private Mimetype(); static Mimetype getInstance(); String getMimetype(Path path); String getMimetype(File file); static final String MIMETYPE_XML; static final String MIMETYPE_HTML; static final String MIMETYPE_OCTET_STREAM; static final String MIMETYPE_GZIP; static final String MIMETYPE_TEXT_PLAIN; static final String MIMETYPE_EVENT_STREAM; }### Answer: @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); }
### Question: UserAgentUtils { static String userAgent() { String ua = UA_STRING; ua = ua .replace("{platform}", "java") .replace("{version}", VersionInfo.SDK_VERSION) .replace("{os.name}", sanitizeInput(JavaSystemSetting.OS_NAME.getStringValue().orElse(null))) .replace("{os.version}", sanitizeInput(JavaSystemSetting.OS_VERSION.getStringValue().orElse(null))) .replace("{java.vm.name}", sanitizeInput(JavaSystemSetting.JAVA_VM_NAME.getStringValue().orElse(null))) .replace("{java.vm.version}", sanitizeInput(JavaSystemSetting.JAVA_VM_VERSION.getStringValue().orElse(null))) .replace("{java.version}", sanitizeInput(JavaSystemSetting.JAVA_VERSION.getStringValue().orElse(null))) .replace("{java.vendor}", sanitizeInput(JavaSystemSetting.JAVA_VENDOR.getStringValue().orElse(null))) .replace("{additional.languages}", getAdditionalJvmLanguages()); Optional<String> language = JavaSystemSetting.USER_LANGUAGE.getStringValue(); Optional<String> region = JavaSystemSetting.USER_REGION.getStringValue(); String languageAndRegion = ""; if (language.isPresent() && region.isPresent()) { languageAndRegion = " (" + sanitizeInput(language.get()) + "_" + sanitizeInput(region.get()) + ")"; } ua = ua.replace("{language.and.region}", languageAndRegion); return ua; } private UserAgentUtils(); static String getUserAgent(); }### Answer: @Test public void userAgent() { String userAgent = UserAgentUtils.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 = UserAgentUtils.userAgent(); System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); assertThat(userAgent).contains("vendor/finks"); } @Test public void userAgent_HasUnknownVendor() { System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); String userAgent = UserAgentUtils.userAgent(); assertThat(userAgent).contains("vendor/unknown"); }
### Question: ByteArrayAsyncRequestBody implements AsyncRequestBody { @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (s == null) { throw new NullPointerException("Subscription MUST NOT be null."); } try { s.onSubscribe( new Subscription() { private boolean done = false; @Override public void request(long n) { if (done) { return; } if (n > 0) { done = true; s.onNext(ByteBuffer.wrap(bytes)); s.onComplete(); } else { s.onError(new IllegalArgumentException("§3.9: non-positive requests are not allowed!")); } } @Override public void cancel() { synchronized (this) { if (!done) { done = true; } } } } ); } catch (Throwable ex) { new IllegalStateException(s + " violated the Reactive Streams rule 2.13 " + "by throwing an exception from onSubscribe.", ex) .printStackTrace(); } } ByteArrayAsyncRequestBody(byte[] bytes); @Override Optional<Long> contentLength(); @Override void subscribe(Subscriber<? super ByteBuffer> s); }### Answer: @Test public void concurrentRequests_shouldCompleteNormally() { ByteArrayAsyncRequestBody byteArrayReq = new ByteArrayAsyncRequestBody("Hello World!".getBytes()); byteArrayReq.subscribe(subscriber); assertTrue(subscriber.onCompleteCalled.get()); }
### Question: ClockSkewAdjuster { public Integer getAdjustmentInSeconds(SdkHttpResponse response) { Instant now = Instant.now(); Instant serverTime = ClockSkew.getServerTime(response).orElse(null); Duration skew = ClockSkew.getClockSkew(now, serverTime); try { return Math.toIntExact(skew.getSeconds()); } catch (ArithmeticException e) { log.warn(() -> "The clock skew between the client and server was too large to be compensated for (" + now + " versus " + serverTime + ")."); return 0; } } boolean shouldAdjust(SdkException exception); Integer getAdjustmentInSeconds(SdkHttpResponse response); }### Answer: @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); }
### Question: FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); @Override InputStream newStream(); }### Answer: @Test public void newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); }
### Question: AwsHostNameUtils { public static Optional<Region> parseSigningRegion(final String host, final String serviceHint) { if (host == null) { throw new IllegalArgumentException("hostname cannot be null"); } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(host); if (matcher.matches()) { return Optional.of(Region.of(matcher.group(1))); } } Pattern pattern = Pattern.compile("^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\."); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return Optional.of(Region.of(matcher.group(1))); } } return Optional.empty(); } private AwsHostNameUtils(); static Optional<Region> parseSigningRegion(final String host, final String serviceHint); }### Answer: @Test public void testStandardNoHint() { assertThat(parseSigningRegion("iam.amazonaws.com", null)).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", null)).hasValue(Region.US_WEST_2); } @Test public void testStandard() { assertThat(parseSigningRegion("iam.amazonaws.com", "iam")).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", "iam")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", "ec2")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); } @Test public void testBjs() { assertThat(parseSigningRegion("iam.cn-north-1.amazonaws.com.cn", "iam")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("ec2.cn-north-1.amazonaws.com.cn", "ec2")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); } @Test public void testParseRegionWithIpv4() { assertThat(parseSigningRegion("54.231.16.200", null)).isNotPresent(); }
### Question: HelpfulUnknownHostExceptionInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!hasCause(context.exception(), UnknownHostException.class)) { return context.exception(); } StringBuilder error = new StringBuilder(); error.append("Received an UnknownHostException when attempting to interact with a service. See cause for the " + "exact endpoint that is failing to resolve. "); Optional<String> globalRegionErrorDetails = getGlobalRegionErrorDetails(executionAttributes); if (globalRegionErrorDetails.isPresent()) { error.append(globalRegionErrorDetails.get()); } else { error.append("If this is happening on an endpoint that previously worked, there may be a network connectivity " + "issue or your DNS cache could be storing endpoints for too long."); } return SdkClientException.builder().message(error.toString()).cause(context.exception()).build(); } @Override Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes); }### Answer: @Test public void modifyException_skipsNonUnknownHostExceptions() { IOException exception = new IOException(); assertThat(modifyException(exception)).isEqualTo(exception); } @Test public void modifyException_supportsNestedUnknownHostExceptions() { Exception exception = new UnknownHostException(); exception.initCause(new IOException()); exception = new IllegalArgumentException(exception); exception = new UnsupportedOperationException(exception); assertThat(modifyException(exception, Region.AWS_GLOBAL)).isInstanceOf(SdkClientException.class); } @Test public void modifyException_returnsGenericHelp_forGlobalRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.AWS_GLOBAL)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forUnknownServices() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forUnknownServicesInUnknownRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forServicesRegionalizedInAllPartitions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "dynamodb")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericGlobalRegionHelp_forServicesGlobalInSomePartitionOtherThanTheClientPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "network")) .hasMessageContaining("aws-global") .hasMessageContaining("aws-cn-global"); } @Test public void modifyException_returnsSpecificGlobalRegionHelp_forServicesGlobalInTheClientRegionPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-1"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "aws-global")) .hasMessageContaining("aws-cn-global"); }
### Question: S3AccessPointResource implements S3Resource, ToCopyableBuilder<S3AccessPointResource.Builder, S3AccessPointResource> { @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } private S3AccessPointResource(Builder b); static Builder builder(); @Override String type(); @Override Optional<S3Resource> parentS3Resource(); @Override Optional<String> partition(); @Override Optional<String> region(); @Override Optional<String> accountId(); String accessPointName(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }### Answer: @Test public void toBuilder() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .region("region") .build() .toBuilder() .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); }
### Question: QueryParametersToBodyInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (!(httpRequest instanceof SdkHttpFullRequest)) { return httpRequest; } SdkHttpFullRequest httpFullRequest = (SdkHttpFullRequest) httpRequest; if (shouldPutParamsInBody(httpFullRequest)) { return changeQueryParametersToFormData(httpFullRequest); } return httpFullRequest; } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }### Answer: @Test public void postRequestsWithNoBodyHaveTheirParametersMovedToTheBody() throws Exception { SdkHttpFullRequest request = requestBuilder.build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); 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(); } @Test public void postWithContentIsUnaltered() throws Exception { byte[] contentBytes = "hello".getBytes(StandardCharsets.UTF_8); ContentStreamProvider contentProvider = () -> new ByteArrayInputStream(contentBytes); SdkHttpFullRequest request = requestBuilder.contentStreamProvider(contentProvider).build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryParameters()).hasSize(1); assertThat(output.headers()).hasSize(0); assertThat(IoUtils.toByteArray(output.contentStreamProvider().get().newStream())).isEqualTo(contentBytes); } @Test public void onlyAlterRequestsIfParamsArePresent() throws Exception { SdkHttpFullRequest request = requestBuilder.clearQueryParameters().build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryParameters()).hasSize(0); assertThat(output.headers()).hasSize(0); assertThat(output.contentStreamProvider()).isEmpty(); }
### Question: ProtocolUtils { public static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint) { SdkHttpFullRequest.Builder request = SdkHttpFullRequest .builder() .method(operationInfo.httpMethod()) .uri(endpoint); return request.encodedPath(SdkHttpUtils.appendUri(request.encodedPath(), addStaticQueryParametersToRequest(request, operationInfo.requestUri()))); } private ProtocolUtils(); static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint); }### Answer: @Test public void createSdkHttpRequest_SetsHttpMethodAndEndpointCorrectly() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .build(), URI.create("http: assertThat(sdkHttpRequest.protocol()).isEqualTo("http"); assertThat(sdkHttpRequest.host()).isEqualTo("localhost"); assertThat(sdkHttpRequest.port()).isEqualTo(8080); assertThat(sdkHttpRequest.method()).isEqualTo(SdkHttpMethod.DELETE); } @Test public void createSdkHttpRequest_EndpointWithPathSetCorrectly() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar"); } @Test public void createSdkHttpRequest_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("/baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); } @Test public void createSdkHttpRequest_NoTrailingSlashInEndpointPath_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("/baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); } @Test public void createSdkHttpRequest_NoLeadingSlashInRequestUri_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); } @Test public void createSdkHttpRequest_NoTrailingOrLeadingSlash_RequestUriAppendedToEndpointPath() { SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest( OperationInfo.builder() .httpMethod(SdkHttpMethod.DELETE) .requestUri("baz") .build(), URI.create("http: assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz"); }
### Question: ProtocolUtils { @SdkTestInternalApi static String addStaticQueryParametersToRequest(SdkHttpFullRequest.Builder request, String uriResourcePath) { if (request == null || uriResourcePath == null) { return null; } String resourcePath = uriResourcePath; int index = resourcePath.indexOf("?"); if (index != -1) { String queryString = resourcePath.substring(index + 1); resourcePath = resourcePath.substring(0, index); for (String s : queryString.split("[;&]")) { index = s.indexOf("="); if (index != -1) { request.putRawQueryParameter(s.substring(0, index), s.substring(index + 1)); } else { request.putRawQueryParameter(s, (String) null); } } } return resourcePath; } private ProtocolUtils(); static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint); }### Answer: @Test public void request_null_returns_null() { Assert.assertNull(ProtocolUtils.addStaticQueryParametersToRequest(null, "foo")); } @Test public void uri_resource_path_null_returns_null() { Assert.assertNull(ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), null)); } @Test public void uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path() { final String uriResourcePath = "/foo/bar"; Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), uriResourcePath)); } @Test public void uri_resource_path_ends_with_question_mark_returns_path_removed_with_question_mark() { final String expectedResourcePath = "/foo/bar"; final String pathWithEmptyStaticQueryParams = expectedResourcePath + "?"; Assert.assertEquals(expectedResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(emptyRequest(), pathWithEmptyStaticQueryParams)); } @Test public void queryparam_value_empty_adds_parameter_with_empty_string_to_request() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1="; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param1")); Assert.assertEquals(singletonList(""), request.rawQueryParameters().get("param1")); } @Test public void static_queryparams_in_path_added_to_request() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param1=value1&param2=value2"; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils .addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param1")); Assert.assertTrue(request.rawQueryParameters().containsKey("param2")); Assert.assertEquals(singletonList("value1"), request.rawQueryParameters().get("param1")); Assert.assertEquals(singletonList("value2"), request.rawQueryParameters().get("param2")); } @Test public void queryparam_without_value_returns_list_containing_null_value() { final String uriResourcePath = "/foo/bar"; final String uriResourcePathWithParams = uriResourcePath + "?param"; SdkHttpFullRequest.Builder request = emptyRequest(); Assert.assertEquals(uriResourcePath, ProtocolUtils.addStaticQueryParametersToRequest(request, uriResourcePathWithParams)); Assert.assertTrue(request.rawQueryParameters().containsKey("param")); Assert.assertEquals(singletonList((String) null), request.rawQueryParameters().get("param")); }
### Question: AwsCborProtocolFactory extends BaseAwsJsonProtocolFactory { @Override protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { if (!isCborEnabled()) { return super.getDefaultTimestampFormats(); } Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS); return Collections.unmodifiableMap(formats); } private AwsCborProtocolFactory(Builder builder); static Builder builder(); }### Answer: @Test public void defaultTimestampFormats_cborEnabled() { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP_MILLIS); } @Test public void defaultTimestampFormats_cborDisabled() { System.setProperty(CBOR_ENABLED.property(), "false"); try { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP); } finally { System.clearProperty(CBOR_ENABLED.property()); } }
### Question: AwsXmlUnmarshallingContext { public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } private AwsXmlUnmarshallingContext(Builder builder); static Builder builder(); SdkHttpFullResponse sdkHttpFullResponse(); XmlElement parsedRootXml(); ExecutionAttributes executionAttributes(); Boolean isResponseSuccess(); XmlElement parsedErrorXml(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); } @Test public void toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); }
### Question: AwsXmlUnmarshallingContext { @Override public int hashCode() { int result = sdkHttpFullResponse != null ? sdkHttpFullResponse.hashCode() : 0; result = 31 * result + (parsedXml != null ? parsedXml.hashCode() : 0); result = 31 * result + (executionAttributes != null ? executionAttributes.hashCode() : 0); result = 31 * result + (isResponseSuccess != null ? isResponseSuccess.hashCode() : 0); result = 31 * result + (parsedErrorXml != null ? parsedErrorXml.hashCode() : 0); return result; } private AwsXmlUnmarshallingContext(Builder builder); static Builder builder(); SdkHttpFullResponse sdkHttpFullResponse(); XmlElement parsedRootXml(); ExecutionAttributes executionAttributes(); Boolean isResponseSuccess(); XmlElement parsedErrorXml(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); } @Test public void hashcode_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); }
### Question: ProfileFileLocation { @SdkInternalApi static String userHomeDirectory() { boolean isWindows = JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); String home = System.getenv("HOME"); if (home != null) { return home; } if (isWindows) { String userProfile = System.getenv("USERPROFILE"); if (userProfile != null) { return userProfile; } String homeDrive = System.getenv("HOMEDRIVE"); String homePath = System.getenv("HOMEPATH"); if (homeDrive != null && homePath != null) { return homeDrive + homePath; } } return JavaSystemSetting.USER_HOME.getStringValueOrThrow(); } private ProfileFileLocation(); static Path configurationFilePath(); static Path credentialsFilePath(); static Optional<Path> configurationFileLocation(); static Optional<Path> credentialsFileLocation(); }### Answer: @Test public void homeDirectoryResolutionPriorityIsCorrectOnWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Windows 7"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("userprofile"); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("homedrivehomepath"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } } @Test public void homeDirectoryResolutionPriorityIsCorrectOnNonWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Linux"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(ProfileFileLocation.userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } }
### Question: ProfileFile { public Map<String, Profile> profiles() { return profiles; } private ProfileFile(Map<String, Map<String, String>> rawProfiles); static Builder builder(); static Aggregator aggregator(); static ProfileFile defaultProfileFile(); Optional<Profile> profile(String profileName); Map<String, Profile> profiles(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void invalidProfilesNamesAreIgnored() { assertThat(aggregateFileProfiles("[profile in valid]\n" + "name = value\n", "[in valid 2]\n" + "name2 = value2")) .isEqualTo(profiles()); } @Test public void configProfilesWithoutPrefixAreIgnored() { assertThat(configFileProfiles("[foo]\n" + "name = value")) .isEqualTo(profiles()); } @Test public void credentialsProfilesWithPrefixAreIgnored() { assertThat(credentialFileProfiles("[profile foo]\n" + "name = value")) .isEqualTo(profiles()); }
### Question: ProfileFile { public static ProfileFile defaultProfileFile() { return ProfileFile.aggregator() .applyMutation(ProfileFile::addCredentialsFile) .applyMutation(ProfileFile::addConfigFile) .build(); } private ProfileFile(Map<String, Map<String, String>> rawProfiles); static Builder builder(); static Aggregator aggregator(); static ProfileFile defaultProfileFile(); Optional<Profile> profile(String profileName); Map<String, Profile> profiles(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void loadingDefaultProfileFileWorks() { ProfileFile.defaultProfileFile(); }
### Question: EnhancedS3ServiceMetadata implements ServiceMetadata { @Override public URI endpointFor(Region region) { if (Region.US_EAST_1.equals(region) && !useUsEast1RegionalEndpoint.getValue()) { return URI.create("s3.amazonaws.com"); } return s3ServiceMetadata.endpointFor(region); } EnhancedS3ServiceMetadata(); private EnhancedS3ServiceMetadata(ServiceMetadataConfiguration config); @Override URI endpointFor(Region region); @Override Region signingRegion(Region region); @Override List<Region> regions(); @Override List<ServicePartitionMetadata> servicePartitions(); @Override ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration); }### Answer: @Test public void optionNotSet_returnsGlobalEndpoint() { assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); } @Test public void regionalSet_profile_returnsRegionalEndpoint() throws URISyntaxException { String testFile = "/profileconfig/s3_regional_config_profile.tst"; System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "regional_s3_endpoint"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), Paths.get(getClass().getResource(testFile).toURI()).toString()); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); } @Test public void regionalSet_env_returnsRegionalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "regional"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); } @Test public void regionalSet_mixedCase_env_returnsRegionalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "rEgIoNaL"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_IAD_REGIONAL_ENDPOINT); } @Test public void global_env_returnsGlobalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "non_regional"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); } @Test public void valueNotEqualToRegional_env_returnsGlobalEndpoint() { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), "some-nonsense-value"); assertThat(enhancedMetadata.endpointFor(Region.US_EAST_1)).isEqualTo(S3_GLOBAL_ENDPOINT); }
### Question: AwsRegionProviderChain implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { List<String> exceptionMessages = null; for (AwsRegionProvider provider : providers) { try { Region region = provider.getRegion(); if (region != null) { return region; } } catch (Exception e) { log.debug("Unable to load region from {}:{}", provider.toString(), e.getMessage()); String message = provider.toString() + ": " + e.getMessage(); if (exceptionMessages == null) { exceptionMessages = new ArrayList<>(); } exceptionMessages.add(message); } } throw SdkClientException.builder() .message("Unable to load region from any of the providers in the chain " + this + ": " + exceptionMessages) .build(); } AwsRegionProviderChain(AwsRegionProvider... providers); @Override Region getRegion(); }### Answer: @Test public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() { AwsRegionProvider providerOne = mock(AwsRegionProvider.class); AwsRegionProvider providerTwo = mock(AwsRegionProvider.class); AwsRegionProvider providerThree = mock(AwsRegionProvider.class); AwsRegionProviderChain chain = new AwsRegionProviderChain(providerOne, providerTwo, providerThree); final Region expectedRegion = Region.of("some-region-string"); when(providerOne.getRegion()).thenReturn(expectedRegion); assertEquals(expectedRegion, chain.getRegion()); verify(providerTwo, never()).getRegion(); verify(providerThree, never()).getRegion(); } @Test public void lastProviderInChainGivesRegionInformation() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } @Test public void providerThrowsException_ContinuesToNextInChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FaultyAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } @Test(expected = Error.class) public void providerThrowsError_DoesNotContinueChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FatalAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } @Test (expected = SdkClientException.class) public void noProviderGivesRegion_ThrowsException() { AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new NeverAwsRegionProvider()); chain.getRegion(); }
### Question: LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); @Override Region getRegion(); @Override String toString(); }### Answer: @Test public void getRegionInvokesSupplierExactlyOnce() { LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor); lazyRegionProvider.getRegion(); lazyRegionProvider.getRegion(); Mockito.verify(regionProviderConstructor, Mockito.times(1)).get(); Mockito.verify(regionProvider, Mockito.times(2)).getRegion(); }
### Question: AwsProfileRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(ProfileProperty.REGION)) .map(Region::of) .orElseThrow(() -> SdkClientException.builder() .message("No region provided in profile: " + profileName) .build()); } AwsProfileRegionProvider(); AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName); @Override Region getRegion(); }### Answer: @Test public void nonExistentDefaultConfigFile_ThrowsException() { settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, "/var/tmp/this/is/invalid.txt"); settingsHelper.set(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE, "/var/tmp/this/is/also.invalid.txt"); assertThatThrownBy(() -> new AwsProfileRegionProvider().getRegion()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("No region provided in profile: default"); } @Test public void profilePresentAndRegionIsSet_ProvidesCorrectRegion() throws URISyntaxException { String testFile = "/profileconfig/test-profiles.tst"; settingsHelper.set(ProfileFileSystemSetting.AWS_PROFILE, "test"); settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, Paths.get(getClass().getResource(testFile).toURI()).toString()); assertThat(new AwsProfileRegionProvider().getRegion()).isEqualTo(Region.of("saa")); }
### Question: EC2MetadataUtils { public static String getToken() { try { return HttpResourcesUtils.instance().readResource(TOKEN_ENDPOINT_PROVIDER, "PUT"); } catch (Exception e) { boolean is400ServiceException = e instanceof SdkServiceException && ((SdkServiceException) e).statusCode() == 400; if (is400ServiceException) { throw SdkClientException.builder() .message("Unable to fetch metadata token") .cause(e) .build(); } return null; } } private EC2MetadataUtils(); static String getAmiId(); static String getAmiLaunchIndex(); static String getAmiManifestPath(); static List<String> getAncestorAmiIds(); static String getInstanceAction(); static String getInstanceId(); static String getInstanceType(); static String getLocalHostName(); static String getMacAddress(); static String getPrivateIpAddress(); static String getAvailabilityZone(); static List<String> getProductCodes(); static String getPublicKey(); static String getRamdiskId(); static String getReservationId(); static List<String> getSecurityGroups(); static IamInfo getIamInstanceProfileInfo(); static InstanceInfo getInstanceInfo(); static String getInstanceSignature(); static String getEC2InstanceRegion(); static Map<String, IamSecurityCredential> getIamSecurityCredentials(); static Map<String, String> getBlockDeviceMapping(); static List<NetworkInterface> getNetworkInterfaces(); static String getUserData(); static String getData(String path); static String getData(String path, int tries); static List<String> getItems(String path); static List<String> getItems(String path, int tries); static String getToken(); }### Answer: @Test public void getToken_queriesCorrectPath() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); String token = EC2MetadataUtils.getToken(); assertThat(token).isEqualTo("some-token"); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); }
### Question: DefaultMetricCollection implements MetricCollection { @SuppressWarnings("unchecked") @Override public <T> List<T> metricValues(SdkMetric<T> metric) { if (metrics.containsKey(metric)) { List<MetricRecord<?>> metricRecords = metrics.get(metric); List<?> values = metricRecords.stream() .map(MetricRecord::value) .collect(toList()); return (List<T>) Collections.unmodifiableList(values); } return Collections.emptyList(); } DefaultMetricCollection(String name, Map<SdkMetric<?>, List<MetricRecord<?>>> metrics, List<MetricCollection> children); @Override String name(); @SuppressWarnings("unchecked") @Override List<T> metricValues(SdkMetric<T> metric); @Override List<MetricCollection> children(); @Override Instant creationTime(); @Override Iterator<MetricRecord<?>> iterator(); @Override String toString(); }### Answer: @Test public void testMetricValues_noValues_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.metricValues(M1)).isEmpty(); }
### Question: DefaultMetricCollection implements MetricCollection { @Override public List<MetricCollection> children() { return children; } DefaultMetricCollection(String name, Map<SdkMetric<?>, List<MetricRecord<?>>> metrics, List<MetricCollection> children); @Override String name(); @SuppressWarnings("unchecked") @Override List<T> metricValues(SdkMetric<T> metric); @Override List<MetricCollection> children(); @Override Instant creationTime(); @Override Iterator<MetricRecord<?>> iterator(); @Override String toString(); }### Answer: @Test public void testChildren_noChildren_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.children()).isEmpty(); }
### Question: DefaultSdkMetric extends AttributeMap.Key<T> implements SdkMetric<T> { public static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, MetricCategory c1, MetricCategory... cn) { Stream<MetricCategory> categoryStream = Stream.of(c1); if (cn != null) { categoryStream = Stream.concat(categoryStream, Stream.of(cn)); } Set<MetricCategory> categories = categoryStream.collect(Collectors.toSet()); return create(name, clzz, level, categories); } private DefaultSdkMetric(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories); @Override String name(); @Override Set<MetricCategory> categories(); @Override MetricLevel level(); @Override Class<T> valueClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, MetricCategory c1, MetricCategory... cn); static SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories); }### Answer: @Test public void testOf_variadicOverload_c1Null_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (MetricCategory) null); } @Test public void testOf_variadicOverload_c1NotNull_cnNull_doesNotThrow() { SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, null); } @Test public void testOf_variadicOverload_cnContainsNull_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, new MetricCategory[]{null }); } @Test public void testOf_setOverload_null_throws() { thrown.expect(NullPointerException.class); thrown.expectMessage("object is null"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (Set<MetricCategory>) null); } @Test public void testOf_setOverload_nullElement_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("categories must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, Stream.of((MetricCategory) null).collect(Collectors.toSet())); } @Test public void testOf_namePreviouslyUsed_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); } @Test public void testOf_namePreviouslyUsed_differentArgs_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Long.class, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); }
### Question: StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); static StaticCredentialsProvider create(AwsCredentials credentials); @Override AwsCredentials resolveCredentials(); @Override String toString(); }### Answer: @Test(expected = RuntimeException.class) public void nullCredentials_ThrowsIllegalArgumentException() { StaticCredentialsProvider.create(null); }
### Question: ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); static Builder builder(); @Override String toString(); }### Answer: @Test(expected = SdkClientException.class) public void testEnvVariableNotSet() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); ContainerCredentialsProvider.builder() .build() .resolveCredentials(); }
### Question: HttpCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { @Override public AwsCredentials resolveCredentials() { if (isLocalCredentialLoadingDisabled()) { throw SdkClientException.builder() .message("Loading credentials from local endpoint is disabled. Unable to load " + "credentials from service endpoint.") .build(); } return credentialsCache.map(CachedSupplier::get).orElseThrow(() -> SdkClientException.builder().message("Unable to load credentials from service endpoint").build()); } protected HttpCredentialsProvider(BuilderImpl<?, ?> builder); HttpCredentialsProvider(boolean asyncCredentialUpdateEnabled, String asyncThreadName); @Override AwsCredentials resolveCredentials(); @Override void close(); }### Answer: @Test public void testLoadCredentialsParsesJsonResponseProperly() { stubForSuccessResponseWithCustomBody(successResponse); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID"); assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); assertThat(credentials.sessionToken()).isEqualTo("TOKEN_TOKEN_TOKEN"); } @Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4)); credentialsProvider.resolveCredentials(); stubForErrorResponse(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); } @Test public void basicCachingFunctionalityWorks() { HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); stubForSuccessResonseWithCustomExpirationDate(Date.from(Instant.now().plus(Duration.ofDays(10)))); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); stubForErrorResponse(); assertThat(credentialsProvider.resolveCredentials()).isNotNull(); }
### Question: LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor); static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor); @Override AwsCredentials resolveCredentials(); @Override void close(); @Override String toString(); }### Answer: @Test public void creationDoesntInvokeSupplier() { LazyAwsCredentialsProvider.create(credentialsConstructor); Mockito.verifyZeroInteractions(credentialsConstructor); }
### Question: ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builder builder(); @Override AwsCredentials resolveCredentials(); @Override String toString(); @Override void close(); }### Answer: @Test public void missingProfileFileThrowsExceptionInGetCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test public void missingProfileThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test public void profileWithoutCredentialsThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); }
### Question: EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); static EventStreamAws4Signer create(); }### Answer: @Test public void openStreamEventSignaturesCanRollOverBetweenDays() { EventStreamAws4Signer signer = EventStreamAws4Signer.create(); Region region = Region.US_WEST_2; AwsCredentials credentials = AwsBasicCredentials.create("a", "s"); String signingName = "name"; AdjustableClock clock = new AdjustableClock(); clock.time = Instant.parse("2020-01-01T23:59:59Z"); SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.GET) .build(); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock, region.id()); ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer(); Callable<ByteBuffer> lastEvent = () -> { clock.time = Instant.parse("2020-01-02T00:00:00Z"); return event; }; AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event), Flowable.fromCallable(lastEvent))); AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials, signingName, clock, region.id()); List<Message> signedMessages = readMessages(signedBody); assertThat(signedMessages.size()).isEqualTo(3); Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders(); assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z"); assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0="); Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders(); assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z"); assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M="); }
### Question: BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer { static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } protected BaseEventStreamAsyncAws4Signer(); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); @Override SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams); static final String EVENT_STREAM_SIGNATURE; static final String EVENT_STREAM_DATE; }### Answer: @Test public void toDebugString_emptyPayload_generatesCorrectString() { Message m = new Message(headers, new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=}"); } @Test public void toDebugString_noHeaders_emptyPayload_generatesCorrectString() { Message m = new Message(new LinkedHashMap<>(), new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={}, payload=}"); } @Test public void toDebugString_largePayload_truncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); byte[] first32 = Arrays.copyOf(payload, 32); String expectedPayloadString = BinaryUtils.toHex(first32); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "...}"); } @Test public void toDebugString_largePayload_noTruncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } @Test public void toDebugString_smallPayload_truncate_doesNotAddEllipsis() { byte[] payload = new byte[8]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); }
### Question: SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); }### Answer: @Test public void isValidForDate_dayBefore_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z"); assertThat(key.isValidForDate(dayBefore)).isFalse(); } @Test public void isValidForDate_sameDay_true() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant sameDay = Instant.parse("2020-03-03T01:02:03Z"); assertThat(key.isValidForDate(sameDay)).isTrue(); } @Test public void isValidForDate_dayAfter_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z"); assertThat(key.isValidForDate(dayAfter)).isFalse(); }
### Question: ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { @Override public Builder toBuilder() { return builder() .resource(resource) .resourceType(resourceType) .qualifier(qualifier); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }### Answer: @Test public void toBuilder() { ArnResource oneResource = ArnResource.fromString("bucket:foobar:1"); ArnResource anotherResource = oneResource.toBuilder().build(); assertThat(oneResource).isEqualTo(anotherResource); assertThat(oneResource.hashCode()).isEqualTo(anotherResource.hashCode()); }
### Question: ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> { public static Builder builder() { return new DefaultBuilder(); } private ArnResource(DefaultBuilder builder); Optional<String> resourceType(); String resource(); Optional<String> qualifier(); static Builder builder(); static ArnResource fromString(String resource); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }### Answer: @Test public void arnResource_nullResource_shouldThrowException() { assertThatThrownBy(() -> ArnResource.builder() .build()).hasMessageContaining("resource must not be null."); }
### Question: Arn implements ToCopyableBuilder<Arn.Builder, Arn> { @Override public Builder toBuilder() { return builder().accountId(accountId) .partition(partition) .region(region) .resource(resource) .service(service) ; } private Arn(DefaultBuilder builder); String partition(); String service(); Optional<String> region(); Optional<String> accountId(); ArnResource resource(); String resourceAsString(); static Builder builder(); static Arn fromString(String arn); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }### Answer: @Test public void toBuilder() { Arn oneArn = Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("bucket:foobar:1") .build(); Arn anotherArn = oneArn.toBuilder().build(); assertThat(oneArn).isEqualTo(anotherArn); assertThat(oneArn.hashCode()).isEqualTo(anotherArn.hashCode()); }
### Question: Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> { public static Builder builder() { return new DefaultBuilder(); } private Http2Configuration(DefaultBuilder builder); Long maxStreams(); Integer initialWindowSize(); Duration healthCheckPingPeriod(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(); }### Answer: @Test public void builder_returnsInstance() { assertThat(Http2Configuration.builder()).isNotNull(); }
### Question: ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); Set<String> nonProxyHosts(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); }### Answer: @Test public void toBuilder_roundTrip_producesExactCopy() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration copy = original.toBuilder().build(); assertThat(copy).isEqualTo(original); } @Test public void toBuilderModified_doesNotModifySource() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build(); assertThat(original).isNotEqualTo(modified); }
### Question: FutureCancelHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (cancelled(ctx, e)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { ctx.fireExceptionCaught(e); } } private FutureCancelHandler(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable e); static FutureCancelHandler getInstance(); }### Answer: @Test public void surfacesCancelExceptionAsIOException() { FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); handler.exceptionCaught(ctx, cancelledException); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isInstanceOf(IOException.class); } @Test public void forwardsExceptionIfNotCancelledException() { ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); Throwable err = new RuntimeException("some other exception"); handler.exceptionCaught(ctx, err); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isEqualTo(err); }
### Question: Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler, InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); }### Answer: @Test public void release_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.release(mockChannel); verify(delegatePool).release(eq(mockChannel), any(Promise.class)); } @Test public void release_withGivenPromise_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); Promise mockPromise = mock(Promise.class); tunnelPool.release(mockChannel, mockPromise); verify(delegatePool).release(eq(mockChannel), eq(mockPromise)); }
### Question: Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler, InitHandlerSupplier initHandlerSupplier); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); }### Answer: @Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.close(); verify(delegatePool).close(); }
### Question: NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); }### Answer: @Test public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() { ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class); when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> { return invocationOnMock.getArgumentAt(0, Promise.class); }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); assertThat(acquireCaptor.getValue().isDone()).isTrue(); assertThat(acquireCaptor.getValue().isSuccess()).isFalse(); } @Test public void cancelExecuteFuture_channelAcquired_submitsRunnable() { EventLoop mockEventLoop = mock(EventLoop.class); Channel mockChannel = mock(Channel.class); when(mockChannel.eventLoop()).thenReturn(mockEventLoop); when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> { Promise p = invocationOnMock.getArgumentAt(0, Promise.class); p.setSuccess(mockChannel); return p; }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); verify(mockEventLoop).submit(any(Runnable.class)); }