Provide method to create TestRestTemplate with basic auth from existing

Closes gh-6732
This commit is contained in:
Andy Wilkinson
2016-08-25 09:41:00 +01:00
parent 2377d78a40
commit 3c5cf02882
2 changed files with 105 additions and 0 deletions

View File

@@ -18,9 +18,11 @@ package org.springframework.boot.test.web.client;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -82,6 +84,8 @@ public class TestRestTemplate {
private final RestTemplate restTemplate;
private final HttpClientOption[] httpClientOptions;
/**
* Create a new {@link TestRestTemplate} instance.
* @param restTemplateBuilder builder used to configure underlying
@@ -118,6 +122,7 @@ public class TestRestTemplate {
public TestRestTemplate(RestTemplate restTemplate, String username, String password,
HttpClientOption... httpClientOptions) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
this.httpClientOptions = httpClientOptions;
if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
restTemplate.setRequestFactory(
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
@@ -900,6 +905,40 @@ public class TestRestTemplate {
return this.restTemplate;
}
/**
* Creates a new {@code TestRestTemplate} with the same configuration as this one,
* except that it will send basic authorization headers using the given
* {@code username} and {@code password}.
* @param username the username
* @param password the password
* @return the new template
* @since 1.4.1
*/
public TestRestTemplate withBasicAuth(String username, String password) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(getRestTemplate().getErrorHandler());
restTemplate.setMessageConverters(getRestTemplate().getMessageConverters());
restTemplate.setInterceptors(
removeBasicAuthInterceptorIfPresent(getRestTemplate().getInterceptors()));
restTemplate.setRequestFactory(getRestTemplate().getRequestFactory());
restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler());
return new TestRestTemplate(restTemplate, username, password,
this.httpClientOptions);
}
private List<ClientHttpRequestInterceptor> removeBasicAuthInterceptorIfPresent(
List<ClientHttpRequestInterceptor> interceptors) {
List<ClientHttpRequestInterceptor> updatedInterceptors = new ArrayList<ClientHttpRequestInterceptor>(
interceptors);
Iterator<ClientHttpRequestInterceptor> iterator = updatedInterceptors.iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BasicAuthorizationInterceptor) {
iterator.remove();
}
}
return interceptors;
}
/**
* Options used to customize the Apache Http Client if it is used.
*/