src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
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 s... | @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() .servi... |
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,
... | @Test public void canConvertStringsWithNonAlphasToClassNames() { String anInvalidClassName = "a phrase-With_other.delimiters"; assertThat(strat.getJavaClassName(anInvalidClassName)).isEqualTo("APhraseWithOtherDelimiters"); }
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithUnderscore() { NamingS... |
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; } DefaultNamingStr... | @Test public void canConvertAuthorizerStartingWithNumber() { String anInvalidClassName = "35-authorizer-implementation"; assertThat(strat.getAuthorizerClassName(anInvalidClassName)).isEqualTo("I35AuthorizerImplementation"); } |
DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(s... | @Test public void test_GetFluentSetterMethodName_NoEnum() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeM... |
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecks... | @Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); Sdk... |
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... | @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(st... |
DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String ge... | @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("FO... |
IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOpe... | @Test public void testServiceAndShapeNameCollisions() throws Exception { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/collision/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.... |
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()... | @Test public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(PutObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-c... |
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 = stri... | @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... |
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()... | @Test public void testUnCapitalize() { capitalizedToUncapitalized.forEach((capitalized,unCapitalized) -> assertThat(Utils.unCapitalize(capitalized), is(equalTo(unCapitalized)))); } |
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); } | @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 nonJavaC... |
ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @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(respon... |
AwsServiceBaseResponseSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkResponseBaseClassName()); } AwsServiceBaseResponseSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void testGeneration() { AwsServiceBaseResponseSpec spec = new AwsServiceBaseResponseSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } |
AwsServiceBaseRequestSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkRequestBaseClassName()); } AwsServiceBaseRequestSpec(IntermediateModel intermediateModel); @Override TypeSpec poetSpec(); @Override ClassName className(); } | @Test public void testGeneration() { AwsServiceBaseRequestSpec spec = new AwsServiceBaseRequestSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } |
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<CodeBl... | @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 = CodeBlo... |
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> ... | @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.o... |
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)", c... | @Test public void syncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/"); EndpointDiscoveryCacheLoaderGenerator cacheLoader = new EndpointDiscoveryCacheLoaderGenerator(... |
Crc32Validation { public static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse) { if (!httpResponse.content().isPresent()) { return httpResponse; } return httpResponse.toBuilder().content( process(calculateCrc32FromCompressedData, httpResponse, httpResponse.conte... | @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") .pu... |
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(); @SdkTestInterna... | @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() { Str... |
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(()... | @Test public void getBucketPolicy_shouldModifyResponseContent() { GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build(); Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder() .statusCode(200) .build()); Optional<InputStream> inputStream = interceptor.modif... |
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 b... | @Test public void equals_emptyList() { assertThat(INSTANCE.equals(new LinkedList<>())).isTrue(); } |
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 co... | @Test public void hashCode_sameAsEmptyList() { assertThat(INSTANCE.hashCode()).isEqualTo(new LinkedList<>().hashCode()); assertThat(INSTANCE.hashCode()).isEqualTo(1); } |
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... | @Test public void toString_emptyList() { assertThat(INSTANCE.toString()).isEqualTo("[]"); } |
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... | @Test public void equal_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.equals(new HashMap<>())).isTrue(); } |
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 ... | @Test public void hashCode_sameAsEmptyMap() { assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(new HashMap<>().hashCode()); assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(0); } |
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 boole... | @Test public void toString_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.toString()).isEqualTo("{}"); } |
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)... | @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.isOutputTo... |
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... | @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(confi... |
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(); Opt... | @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... |
AsyncStreamingRequestMarshaller extends AbstractStreamingRequestMarshaller<T> { @Override public SdkHttpFullRequest marshall(T in) { SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder(); addHeaders(marshalled, asyncRequestBody.contentLength(), requiresLength, transferEncoding, useHttp2); ... | @Test public void contentLengthIsPresent_shouldNotOverride() { long contentLengthOnRequest = 1L; long contengLengthOnRequestBody = 5L; when(requestBody.contentLength()).thenReturn(Optional.of(contengLengthOnRequestBody)); AsyncStreamingRequestMarshaller marshaller = createMarshaller(true, true, true); SdkHttpFullReques... |
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();... | @Test public void totalRequests_IsOneMoreThanRetriesAttempted() { assertEquals(4, RetryPolicyContexts.withRetriesAttempted(3).totalRequests()); } |
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(); ... | @Test public void nullHttpStatusCodeAllowed() { assertNull(RetryPolicyContexts.withStatusCode(null).httpStatusCode()); } |
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(); Execu... | @Test public void nullExceptionAllowed() { assertNull(RetryPolicyContexts.withException(null).exception()); } |
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); @Over... | @Test public void missingAttemptsExecuted_shouldThrowException() { assertThatThrownBy(() -> DefaultWaiterResponse.<String>builder().response("foobar") .build()).hasMessageContaining("attemptsExecuted"); } |
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 S3AccessP... | @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(s3AccessPointReso... |
MakeHttpRequestStage implements RequestPipeline<SdkHttpFullRequest, Pair<SdkHttpFullRequest, SdkHttpFullResponse>> { public Pair<SdkHttpFullRequest, SdkHttpFullResponse> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { InterruptMonitor.checkInterrupted(); HttpExecuteResponse execu... | @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); Metric... |
MakeAsyncHttpRequestStage implements RequestPipeline<CompletableFuture<SdkHttpFullRequest>, CompletableFuture<Response<OutputT>>> { @Override public CompletableFuture<Response<OutputT>> execute(CompletableFuture<SdkHttpFullRequest> requestFuture, RequestExecutionContext context) { CompletableFuture<Response<OutputT>> t... | @Test public void apiCallAttemptTimeoutEnabled_shouldInvokeExecutor() throws Exception { stage = new MakeAsyncHttpRequestStage<>( combinedAsyncResponseHandler(AsyncResponseHandlerTestUtils.noOpResponseHandler(), AsyncResponseHandlerTestUtils.noOpResponseHandler()), clientDependencies(Duration.ofMillis(1000))); Completa... |
TimeoutExceptionHandlingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { return requestPipeline.execute(request, context); } catch (Exception e) { throw translatePipelineException(contex... | @Test public void IOException_causedByApiCallTimeout_shouldThrowInterruptedException() throws Exception { when(apiCallTimeoutTask.hasExecuted()).thenReturn(true); when(requestPipeline.execute(any(), any())).thenThrow(new SocketException()); verifyExceptionThrown(InterruptedException.class); }
@Test public void IOExcept... |
S3ArnUtils { public static IntermediateOutpostResource parseOutpostArn(Arn arn) { String resource = arn.resourceAsString(); Integer outpostIdEndIndex = null; for (int i = OUTPOST_ID_START_INDEX; i < resource.length(); ++i) { char ch = resource.charAt(i); if (ch == ':' || ch == '/') { outpostIdEndIndex = i; break; } } i... | @Test public void parseOutpostArn_arnWithColon_shouldParseCorrectly() { IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:22222:accesspoint:foobar") .build()); assertThat(... |
ApiCallAttemptTimeoutTrackingStage implements RequestToResponsePipeline<OutputT> { @Override public Response<OutputT> execute(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception { try { long timeoutInMillis = resolveTimeoutInMillis(context.requestConfig()::apiCallAttemptTimeout, apiCallAttempt... | @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); Request... |
AsyncApiCallTimeoutTrackingStage implements RequestPipeline<SdkHttpFullRequest, CompletableFuture<OutputT>> { @Override public CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context) throws Exception { CompletableFuture<OutputT> future = new CompletableFuture<>(); long apiCallTimeo... | @Test @SuppressWarnings("unchecked") public void testSchedulesTheTimeoutUsingSuppliedExecutorService() throws Exception { AsyncApiCallTimeoutTrackingStage apiCallTimeoutTrackingStage = new AsyncApiCallTimeoutTrackingStage(dependencies, requestPipeline); apiCallTimeoutTrackingStage.execute(httpRequest, requestExecutionC... |
MergeCustomHeadersStage implements MutableRequestToRequestPipeline { @Override public SdkHttpFullRequest.Builder execute(SdkHttpFullRequest.Builder request, RequestExecutionContext context) throws Exception { return request.headers(mergeHeaders(request.headers(), config.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS), ... | @Test public void singleHeader_inMarshalledRequest_overriddenOnClient() throws Exception { SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder(); RequestExecutionContext ctx = requestContext(NoopTestRequest.builder().build()); requestBuilder.putHeader(singleHeaderName, "marshaller"); Map<String, List... |
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); } ... | @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(() -... |
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> loadServ... | @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"); ... |
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>... ... | @Test public void allProvidersReturnEmpty_ReturnsEmptyOptional() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.empty()); when(delegate... |
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); @Overrid... | @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()... |
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 SdkC... | @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)... |
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, Du... | @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"; }); a... |
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<... | @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; } } |
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... | @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.bui... |
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); s... | @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_defaulttoB... |
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.getS... | @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 u... |
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) {... | @Test public void concurrentRequests_shouldCompleteNormally() { ByteArrayAsyncRequestBody byteArrayReq = new ByteArrayAsyncRequestBody("Hello World!".getBytes()); byteArrayReq.subscribe(subscriber); assertTrue(subscriber.onCompleteCalled.get()); } |
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... | @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 farFutureDateTranslat... |
FileContentStreamProvider implements ContentStreamProvider { @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } FileContentStreamProvider(Path filePath); @Override InputStream newStream(); } | @Test public void newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); } |
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 parseStandardRegio... | @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); a... |
HelpfulUnknownHostExceptionInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!hasCause(context.exception(), UnknownHostException.class)) { return context.exception(); } StringBuilder error = new String... | @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(ne... |
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); stati... | @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()... |
QueryParametersToBodyInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (!(httpRequest instanceof SdkHttpFullRequest)) { return httpRequest; }... | @Test public void postRequestsWithNoBodyHaveTheirParametersMovedToTheBody() throws Exception { SdkHttpFullRequest request = requestBuilder.build(); SdkHttpFullRequest output = (SdkHttpFullRequest) interceptor.modifyHttpRequest( new HttpRequestOnlyContext(request, null), executionAttributes); assertThat(output.rawQueryP... |
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(), addSt... | @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(sdkHttpR... |
S3ArnConverter implements ArnConverter<S3Resource> { @Override public S3Resource convertArn(Arn arn) { if (isV1Arn(arn)) { return convertV1Arn(arn); } S3ResourceType s3ResourceType; String resourceType = arn.resource().resourceType().orElseThrow(() -> new IllegalArgumentException("Unknown ARN type")); try { s3ResourceT... | @Test public void parseArn_objectThroughAp_v2Arn() { S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("accesspoint:test-ap/object/test-key") .build()); assertThat(resource, instanceOf(S3ObjectResource.class)); S3Objec... |
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 query... | @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_do... |
AwsCborProtocolFactory extends BaseAwsJsonProtocolFactory { @Override protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { if (!isCborEnabled()) { return super.getDefaultTimestampFormats(); } Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocati... | @Test public void defaultTimestampFormats_cborEnabled() { Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats(); assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822); assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOA... |
AwsXmlUnmarshallingContext { public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } private AwsXmlUnmarshallingContext(Builde... | @Test public void toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); }
@Test public void toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); } |
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 * re... | @Test public void hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); }
@Test public void hashcode_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); } |
JsonDomParser { public SdkJsonNode parse(InputStream content) throws IOException { try (JsonParser parser = jsonFactory.createParser(content) .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) { return parseToken(parser, parser.nextToken()); } } private JsonDomParser(JsonFactory jsonFactory); SdkJsonNode parse(I... | @Test public void simpleString_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("\"foo\""); assertThat(node) .isInstanceOf(SdkScalarNode.class) .matches(s -> ((SdkScalarNode) s).value().equals("foo")); }
@Test public void simpleNumber_ParsedCorrectly() throws IOException { SdkJsonNode node = parse("42");... |
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 =... | @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_H... |
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();... | @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")) .isEqual... |
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... | @Test public void loadingDefaultProfileFileWorks() { ProfileFile.defaultProfileFile(); } |
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 Enhance... | @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.setPr... |
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... | @Test public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() { AwsRegionProvider providerOne = mock(AwsRegionProvider.class); AwsRegionProvider providerTwo = mock(AwsRegionProvider.class); AwsRegionProvider providerThree = mock(AwsRegionProvider.class); AwsRegionProviderChain chain = new ... |
LazyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() { return delegate.getValue().getRegion(); } LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor); @Override Region getRegion(); @Override String toString(); } | @Test public void getRegionInvokesSupplierExactlyOnce() { LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor); lazyRegionProvider.getRegion(); lazyRegionProvider.getRegion(); Mockito.verify(regionProviderConstructor, Mockito.times(1)).get(); Mockito.verify(regionProvider, Moc... |
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) .b... | @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 AwsProfileRegionPro... |
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 SdkC... | @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_M... |
EC2MetadataUtils { public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } private EC2MetadataUtils(); static String getAmiId(); static String getAmiLaunchIndex(); static String getAmiManifestPath(); static List<String> getAncestorAmiIds(); static String getInstanceAction(); static String ... | @Test public void getAmiId_queriesAndIncludesToken() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN... |
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(t... | @Test public void testMetricValues_noValues_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.metricValues(M1)).isEmpty(); } |
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... | @Test public void testChildren_noChildren_returnsEmptyList() { DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList()); assertThat(foo.children()).isEmpty(); } |
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, S... | @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(... |
StaticCredentialsProvider implements AwsCredentialsProvider { public static StaticCredentialsProvider create(AwsCredentials credentials) { return new StaticCredentialsProvider(credentials); } private StaticCredentialsProvider(AwsCredentials credentials); static StaticCredentialsProvider create(AwsCredentials credentia... | @Test(expected = RuntimeException.class) public void nullCredentials_ThrowsIllegalArgumentException() { StaticCredentialsProvider.create(null); } |
InstanceProfileCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private InstanceProfileCredentialsProvider(BuilderImpl builder); static Builder builder(); static InstanceProfileCredentialsProvider create(); @Override String toString(); } | @Test public void resolveCredentials_metadataLookupDisabled_throws() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); thrown.expect(SdkClientException.class); thrown.expectMessage("Loading credentials from local endpoint is disabled"); try { InstanceProfileCredentialsProvider.builder... |
ContainerCredentialsProvider extends HttpCredentialsProvider { public static Builder builder() { return new BuilderImpl(); } private ContainerCredentialsProvider(BuilderImpl builder); static Builder builder(); @Override String toString(); } | @Test(expected = SdkClientException.class) public void testEnvVariableNotSet() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); ContainerCredentialsProvider.builder() .build() .resolveCredentials(); } |
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 en... | @Test public void testLoadCredentialsParsesJsonResponseProperly() { stubForSuccessResponseWithCustomBody(successResponse); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(credentials... |
LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) { return new LazyAwsCredentialsProvider(delegateConstructor); } private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> dele... | @Test public void creationDoesntInvokeSupplier() { LazyAwsCredentialsProvider.create(credentialsConstructor); Mockito.verifyZeroInteractions(credentialsConstructor); } |
ProfileCredentialsUtils { public Optional<AwsCredentialsProvider> credentialsProvider() { return credentialsProvider(new HashSet<>()); } ProfileCredentialsUtils(Profile profile, Function<String, Optional<Profile>> credentialsSourceResolver); Optional<AwsCredentialsProvider> credentialsProvider(); } | @Test public void profileFileWithStaticCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("default")).hasValueSatisfying(profile -> { assertThat(profile.name()).isEqualTo("default"); assertThat(profile.property(ProfileProperty.AWS_ACCESS_KEY_ID)).hasValue("defaultA... |
ProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { public static Builder builder() { return new BuilderImpl(); } private ProfileCredentialsProvider(BuilderImpl builder); static ProfileCredentialsProvider create(); static ProfileCredentialsProvider create(String profileName); static Builde... | @Test public void missingProfileFileThrowsExceptionInGetCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownB... |
Aws4Signer extends BaseAws4Signer { public static Aws4Signer create() { return new Aws4Signer(); } private Aws4Signer(); static Aws4Signer create(); } | @Test public void testSigning() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b786... |
EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer { public static EventStreamAws4Signer create() { return new EventStreamAws4Signer(); } private EventStreamAws4Signer(); static EventStreamAws4Signer create(); } | @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... |
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().iterat... | @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 toDebugStr... |
SignerKey { public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } SignerKey(Instant date, byte[] signingKey); boolean isValidForDate(Instant other); byte[] getSigningKey(); } | @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_same... |
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>... | @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()); } |
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 fromS... | @Test public void arnResource_nullResource_shouldThrowException() { assertThatThrownBy(() -> ArnResource.builder() .build()).hasMessageContaining("resource must not be null."); } |
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(); Optiona... | @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.has... |
Arn implements ToCopyableBuilder<Arn.Builder, Arn> { public static Arn fromString(String arn) { int arnColonIndex = arn.indexOf(':'); if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) { throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'"); } int partitionColonIndex = ar... | @Test public void arnWithoutPartition_ThrowsIllegalArgumentException() { String arnString = "arn::s3:us-east-1:12345678910:myresource"; assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("artition must not be blank or empty."); }
@Test public void arnWithoutService_ThrowsIllegalArgumentException()... |
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 toBu... | @Test public void builder_returnsInstance() { assertThat(Http2Configuration.builder()).isNotNull(); } |
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(Obj... | @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 = allPropertiesSetCo... |
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(... | @Test public void surfacesCancelExceptionAsIOException() { FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); handler.exceptionCaught(ctx, cancelledException); verify(ctx).fire... |
Http1TunnelConnectionPool implements ChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandl... | @Test public void tunnelAlreadyEstablished_doesNotAddInitHandler() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); when(mockAttr.get()).thenReturn(true); tunnelPool.acquire().awaitUninterruptibly(); verify(mockPip... |
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 remoteAddr... | @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... |
Http1TunnelConnectionPool implements ChannelPool { @Override public void close() { delegate.close(); } Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler); @SdkTestInternalApi H... | @Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler); tunnelPool.close(); verify(delegatePool).close(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.