Develop fill ut common (#11419)
* UT for common module http package. * Add Unit test for common module http root package. * Add Unit test for common module http param package. * Add Unit test for common module http client package. * For checkstyle.
This commit is contained in:
parent
15c48f4246
commit
7ce177486f
@ -77,7 +77,7 @@ public class ConfigHttpClientManager implements Closeable {
|
|||||||
public void shutdown() throws NacosException {
|
public void shutdown() throws NacosException {
|
||||||
NAMING_LOGGER.warn("[ConfigHttpClientManager] Start destroying NacosRestTemplate");
|
NAMING_LOGGER.warn("[ConfigHttpClientManager] Start destroying NacosRestTemplate");
|
||||||
try {
|
try {
|
||||||
HttpClientBeanHolder.shutdownNacostSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
NAMING_LOGGER.error("[ConfigHttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
NAMING_LOGGER.error("[ConfigHttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
||||||
ExceptionUtil.getStackTrace(ex));
|
ExceptionUtil.getStackTrace(ex));
|
||||||
|
@ -73,7 +73,7 @@ public class NamingHttpClientManager implements Closeable {
|
|||||||
public void shutdown() throws NacosException {
|
public void shutdown() throws NacosException {
|
||||||
NAMING_LOGGER.warn("[NamingHttpClientManager] Start destroying NacosRestTemplate");
|
NAMING_LOGGER.warn("[NamingHttpClientManager] Start destroying NacosRestTemplate");
|
||||||
try {
|
try {
|
||||||
HttpClientBeanHolder.shutdownNacostSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
NAMING_LOGGER.error("[NamingHttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
NAMING_LOGGER.error("[NamingHttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
||||||
ExceptionUtil.getStackTrace(ex));
|
ExceptionUtil.getStackTrace(ex));
|
||||||
|
@ -62,6 +62,18 @@
|
|||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<version>1.2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<resources>
|
<resources>
|
||||||
|
@ -196,9 +196,6 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
|
|||||||
|
|
||||||
@SuppressWarnings("checkstyle:abbreviationaswordinname")
|
@SuppressWarnings("checkstyle:abbreviationaswordinname")
|
||||||
protected synchronized SSLContext loadSSLContext() {
|
protected synchronized SSLContext loadSSLContext() {
|
||||||
if (!TlsSystemConfig.tlsEnable) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
return TlsHelper.buildSslContext(true);
|
return TlsHelper.buildSslContext(true);
|
||||||
} catch (NoSuchAlgorithmException | KeyManagementException e) {
|
} catch (NoSuchAlgorithmException | KeyManagementException e) {
|
||||||
|
@ -118,7 +118,7 @@ public final class HttpClientBeanHolder {
|
|||||||
* @throws Exception ex
|
* @throws Exception ex
|
||||||
*/
|
*/
|
||||||
public static void shutdown(String className) throws Exception {
|
public static void shutdown(String className) throws Exception {
|
||||||
shutdownNacostSyncRest(className);
|
shutdownNacosSyncRest(className);
|
||||||
shutdownNacosAsyncRest(className);
|
shutdownNacosAsyncRest(className);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -128,7 +128,7 @@ public final class HttpClientBeanHolder {
|
|||||||
* @param className HttpClientFactory implement class name
|
* @param className HttpClientFactory implement class name
|
||||||
* @throws Exception ex
|
* @throws Exception ex
|
||||||
*/
|
*/
|
||||||
public static void shutdownNacostSyncRest(String className) throws Exception {
|
public static void shutdownNacosSyncRest(String className) throws Exception {
|
||||||
final NacosRestTemplate nacosRestTemplate = SINGLETON_REST.get(className);
|
final NacosRestTemplate nacosRestTemplate = SINGLETON_REST.get(className);
|
||||||
if (nacosRestTemplate != null) {
|
if (nacosRestTemplate != null) {
|
||||||
nacosRestTemplate.close();
|
nacosRestTemplate.close();
|
||||||
|
@ -66,9 +66,6 @@ public class JdkHttpClientResponse implements HttpClientResponse {
|
|||||||
// Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream
|
// Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream
|
||||||
if (CONTENT_ENCODING.equals(contentEncoding)) {
|
if (CONTENT_ENCODING.equals(contentEncoding)) {
|
||||||
byte[] bytes = IoUtils.tryDecompress(this.responseStream);
|
byte[] bytes = IoUtils.tryDecompress(this.responseStream);
|
||||||
if (bytes == null) {
|
|
||||||
throw new IOException("decompress http response error");
|
|
||||||
}
|
|
||||||
return new ByteArrayInputStream(bytes);
|
return new ByteArrayInputStream(bytes);
|
||||||
}
|
}
|
||||||
return this.responseStream;
|
return this.responseStream;
|
||||||
|
@ -1,32 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.alibaba.nacos.common.http.handler;
|
|
||||||
|
|
||||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request handler.
|
|
||||||
*
|
|
||||||
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
|
|
||||||
*/
|
|
||||||
public final class RequestHandler {
|
|
||||||
|
|
||||||
public static String parse(Object object) throws Exception {
|
|
||||||
return JacksonUtils.toJson(object);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.alibaba.nacos.common.http.handler;
|
|
||||||
|
|
||||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
|
||||||
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.lang.reflect.Type;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response handler.
|
|
||||||
*
|
|
||||||
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
|
|
||||||
*/
|
|
||||||
public final class ResponseHandler {
|
|
||||||
|
|
||||||
public static <T> T convert(String s, Class<T> cls) throws Exception {
|
|
||||||
return JacksonUtils.toObj(s, cls);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T convert(String s, Type type) throws Exception {
|
|
||||||
return JacksonUtils.toObj(s, type);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T convert(InputStream inputStream, Type type) throws Exception {
|
|
||||||
return JacksonUtils.toObj(inputStream, type);
|
|
||||||
}
|
|
||||||
}
|
|
@ -42,14 +42,11 @@ public class Header {
|
|||||||
|
|
||||||
private static final String DEFAULT_CHARSET = "UTF-8";
|
private static final String DEFAULT_CHARSET = "UTF-8";
|
||||||
|
|
||||||
private static final String DEFAULT_ENCODING = "gzip";
|
|
||||||
|
|
||||||
private Header() {
|
private Header() {
|
||||||
header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||||
originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||||
addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_JSON);
|
addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_JSON);
|
||||||
addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET);
|
addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET);
|
||||||
//addParam(HttpHeaderConsts.ACCEPT_ENCODING, DEFAULT_ENCODING);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Header newInstance() {
|
public static Header newInstance() {
|
||||||
@ -59,7 +56,7 @@ public class Header {
|
|||||||
/**
|
/**
|
||||||
* Add the key and value to the header.
|
* Add the key and value to the header.
|
||||||
*
|
*
|
||||||
* @param key the key
|
* @param key the key
|
||||||
* @param value the value
|
* @param value the value
|
||||||
* @return header
|
* @return header
|
||||||
*/
|
*/
|
||||||
@ -77,10 +74,6 @@ public class Header {
|
|||||||
return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType);
|
return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Header build() {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getValue(String key) {
|
public String getValue(String key) {
|
||||||
return header.get(key);
|
return header.get(key);
|
||||||
}
|
}
|
||||||
@ -146,7 +139,7 @@ public class Header {
|
|||||||
*
|
*
|
||||||
* <p>Currently only corresponds to the response header of JDK.
|
* <p>Currently only corresponds to the response header of JDK.
|
||||||
*
|
*
|
||||||
* @param key original response header key
|
* @param key original response header key
|
||||||
* @param values original response header values
|
* @param values original response header values
|
||||||
*/
|
*/
|
||||||
public void addOriginalResponseHeader(String key, List<String> values) {
|
public void addOriginalResponseHeader(String key, List<String> values) {
|
||||||
@ -179,7 +172,7 @@ public class Header {
|
|||||||
private String analysisCharset(String contentType) {
|
private String analysisCharset(String contentType) {
|
||||||
String[] values = contentType.split(";");
|
String[] values = contentType.split(";");
|
||||||
String charset = Constants.ENCODE;
|
String charset = Constants.ENCODE;
|
||||||
if (values.length == 0) {
|
if (values.length == 1) {
|
||||||
return charset;
|
return charset;
|
||||||
}
|
}
|
||||||
for (String value : values) {
|
for (String value : values) {
|
||||||
|
@ -21,7 +21,6 @@ import com.alibaba.nacos.common.utils.MapUtil;
|
|||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@ -80,20 +79,6 @@ public class Query {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Add query parameters from KV list. KV list: odd index is key, even index is value.
|
|
||||||
*
|
|
||||||
* @param list KV list
|
|
||||||
*/
|
|
||||||
public void initParams(List<String> list) {
|
|
||||||
if ((list.size() & 1) != 0) {
|
|
||||||
throw new IllegalArgumentException("list size must be a multiple of 2");
|
|
||||||
}
|
|
||||||
for (int i = 0; i < list.size(); ) {
|
|
||||||
addParam(list.get(i++), list.get(i++));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Print query as a http url param string. Like K=V&K=V.
|
* Print query as a http url param string. Like K=V&K=V.
|
||||||
*
|
*
|
||||||
@ -122,8 +107,8 @@ public class Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void clear() {
|
public void clear() {
|
||||||
isEmpty = false;
|
|
||||||
params.clear();
|
params.clear();
|
||||||
|
isEmpty = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEmpty() {
|
public boolean isEmpty() {
|
||||||
|
@ -0,0 +1,69 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||||
|
import com.alibaba.nacos.common.http.client.request.DefaultHttpClientRequest;
|
||||||
|
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class AbstractApacheHttpClientFactoryTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Logger logger;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCreateNacosRestTemplate() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
HttpClientFactory factory = new AbstractApacheHttpClientFactory() {
|
||||||
|
@Override
|
||||||
|
protected HttpClientConfig buildHttpClientConfig() {
|
||||||
|
return HttpClientConfig.builder().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Logger assignLogger() {
|
||||||
|
return logger;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
NacosRestTemplate template = factory.createNacosRestTemplate();
|
||||||
|
assertNotNull(template);
|
||||||
|
Field field = NacosRestTemplate.class.getDeclaredField("requestClient");
|
||||||
|
field.setAccessible(true);
|
||||||
|
HttpClientRequest requestClient = (HttpClientRequest) field.get(template);
|
||||||
|
assertTrue(requestClient instanceof DefaultHttpClientRequest);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
|
||||||
|
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||||
|
import com.alibaba.nacos.common.tls.TlsSystemConfig;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class AbstractHttpClientFactoryTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Logger logger;
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
TlsSystemConfig.tlsEnable = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCreateNacosRestTemplateWithSsl() throws Exception {
|
||||||
|
TlsSystemConfig.tlsEnable = true;
|
||||||
|
HttpClientFactory httpClientFactory = new DefaultHttpClientFactory(logger);
|
||||||
|
NacosRestTemplate nacosRestTemplate = httpClientFactory.createNacosRestTemplate();
|
||||||
|
assertNotNull(nacosRestTemplate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCreateNacosAsyncRestTemplate() {
|
||||||
|
HttpClientFactory httpClientFactory = new AbstractHttpClientFactory() {
|
||||||
|
@Override
|
||||||
|
protected HttpClientConfig buildHttpClientConfig() {
|
||||||
|
return HttpClientConfig.builder().setMaxConnTotal(10).setMaxConnPerRoute(10).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Logger assignLogger() {
|
||||||
|
return logger;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
NacosAsyncRestTemplate nacosRestTemplate = httpClientFactory.createNacosAsyncRestTemplate();
|
||||||
|
assertNotNull(nacosRestTemplate);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,105 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import org.apache.http.client.methods.HttpRequestBase;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BaseHttpMethodTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpGet() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.GET;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("GET", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpGetLarge() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.GET_LARGE;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("GET", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpPost() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.POST;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("POST", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpPut() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.PUT;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("PUT", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpDelete() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.DELETE;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("DELETE", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpDeleteLarge() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.DELETE_LARGE;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("DELETE", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpHead() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.HEAD;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("HEAD", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpTrace() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.TRACE;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("TRACE", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpPatch() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.PATCH;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("PATCH", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHttpOptions() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.OPTIONS;
|
||||||
|
HttpRequestBase request = method.init("http://example.com");
|
||||||
|
Assert.assertEquals("TRACE", request.getMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSourceOf() {
|
||||||
|
BaseHttpMethod method = BaseHttpMethod.sourceOf("GET");
|
||||||
|
Assert.assertEquals(BaseHttpMethod.GET, method);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void testSourceOfNotFound() {
|
||||||
|
BaseHttpMethod.sourceOf("Not Found");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,145 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
|
||||||
|
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class HttpClientBeanHolderTest {
|
||||||
|
|
||||||
|
private Map<String, NacosRestTemplate> cachedRestTemplateMap;
|
||||||
|
|
||||||
|
private Map<String, NacosRestTemplate> restMap;
|
||||||
|
|
||||||
|
private Map<String, NacosAsyncRestTemplate> cachedAsyncRestTemplateMap;
|
||||||
|
|
||||||
|
private Map<String, NacosAsyncRestTemplate> restAsyncMap;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private NacosRestTemplate mockRestTemplate;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private NacosAsyncRestTemplate mockAsyncRestTemplate;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientFactory mockFactory;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
cachedRestTemplateMap = new HashMap<>();
|
||||||
|
cachedAsyncRestTemplateMap = new HashMap<>();
|
||||||
|
restMap = (Map<String, NacosRestTemplate>) getCachedMap("SINGLETON_REST");
|
||||||
|
restAsyncMap = (Map<String, NacosAsyncRestTemplate>) getCachedMap("SINGLETON_ASYNC_REST");
|
||||||
|
cachedRestTemplateMap.putAll(restMap);
|
||||||
|
cachedAsyncRestTemplateMap.putAll(restAsyncMap);
|
||||||
|
restMap.clear();
|
||||||
|
restAsyncMap.clear();
|
||||||
|
when(mockFactory.createNacosRestTemplate()).thenReturn(mockRestTemplate);
|
||||||
|
when(mockFactory.createNacosAsyncRestTemplate()).thenReturn(mockAsyncRestTemplate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
restMap.putAll(cachedRestTemplateMap);
|
||||||
|
restAsyncMap.putAll(cachedAsyncRestTemplateMap);
|
||||||
|
cachedRestTemplateMap.clear();
|
||||||
|
cachedAsyncRestTemplateMap.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object getCachedMap(String mapName) throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
Field field = HttpClientBeanHolder.class.getDeclaredField(mapName);
|
||||||
|
field.setAccessible(true);
|
||||||
|
return field.get(HttpClientBeanHolder.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetNacosRestTemplateWithDefault() {
|
||||||
|
assertTrue(restMap.isEmpty());
|
||||||
|
NacosRestTemplate actual = HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restMap.size());
|
||||||
|
NacosRestTemplate duplicateGet = HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restMap.size());
|
||||||
|
assertEquals(actual, duplicateGet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void testGetNacosRestTemplateForNullFactory() {
|
||||||
|
HttpClientBeanHolder.getNacosRestTemplate((HttpClientFactory) null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetNacosRestTemplateWithCustomFactory() {
|
||||||
|
assertTrue(restMap.isEmpty());
|
||||||
|
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restMap.size());
|
||||||
|
NacosRestTemplate actual = HttpClientBeanHolder.getNacosRestTemplate(mockFactory);
|
||||||
|
assertEquals(2, restMap.size());
|
||||||
|
assertEquals(mockRestTemplate, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetNacosAsyncRestTemplateWithDefault() {
|
||||||
|
assertTrue(restAsyncMap.isEmpty());
|
||||||
|
NacosAsyncRestTemplate actual = HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restAsyncMap.size());
|
||||||
|
NacosAsyncRestTemplate duplicateGet = HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restAsyncMap.size());
|
||||||
|
assertEquals(actual, duplicateGet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void testGetNacosAsyncRestTemplateForNullFactory() {
|
||||||
|
HttpClientBeanHolder.getNacosAsyncRestTemplate((HttpClientFactory) null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetNacosAsyncRestTemplateWithCustomFactory() {
|
||||||
|
assertTrue(restAsyncMap.isEmpty());
|
||||||
|
HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restAsyncMap.size());
|
||||||
|
NacosAsyncRestTemplate actual = HttpClientBeanHolder.getNacosAsyncRestTemplate(mockFactory);
|
||||||
|
assertEquals(2, restAsyncMap.size());
|
||||||
|
assertEquals(mockAsyncRestTemplate, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shutdown() throws Exception {
|
||||||
|
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||||
|
HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||||
|
assertEquals(1, restMap.size());
|
||||||
|
assertEquals(1, restAsyncMap.size());
|
||||||
|
HttpClientBeanHolder.shutdown(DefaultHttpClientFactory.class.getName());
|
||||||
|
assertEquals(0, restMap.size());
|
||||||
|
assertEquals(0, restAsyncMap.size());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,94 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
public class HttpClientConfigTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetConTimeOutMillis() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
assertEquals(1000, config.getConTimeOutMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetReadTimeOutMillis() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setReadTimeOutMillis(2000).build();
|
||||||
|
assertEquals(2000, config.getReadTimeOutMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetConnTimeToLive() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS)
|
||||||
|
.build();
|
||||||
|
assertEquals(3000, config.getConnTimeToLive());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetConnTimeToLiveTimeUnit() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(4000, TimeUnit.SECONDS).build();
|
||||||
|
assertEquals(TimeUnit.SECONDS, config.getConnTimeToLiveTimeUnit());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetConnectionRequestTimeout() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConnectionRequestTimeout(5000).build();
|
||||||
|
assertEquals(5000, config.getConnectionRequestTimeout());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetMaxRedirects() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setMaxRedirects(60).build();
|
||||||
|
assertEquals(60, config.getMaxRedirects());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetMaxConnTotal() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setMaxConnTotal(70).build();
|
||||||
|
assertEquals(70, config.getMaxConnTotal());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetMaxConnPerRoute() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setMaxConnPerRoute(80).build();
|
||||||
|
assertEquals(80, config.getMaxConnPerRoute());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetContentCompressionEnabled() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setContentCompressionEnabled(false).build();
|
||||||
|
assertFalse(config.getContentCompressionEnabled());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetIoThreadCount() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setIoThreadCount(90).build();
|
||||||
|
assertEquals(90, config.getIoThreadCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetUserAgent() {
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setUserAgent("testUserAgent").build();
|
||||||
|
assertEquals("testUserAgent", config.getUserAgent());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class HttpRestResultTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSetHeader() {
|
||||||
|
HttpRestResult<String> result = new HttpRestResult<>();
|
||||||
|
result.setData("test data");
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
result.setHeader(header);
|
||||||
|
assertEquals(header, result.getHeader());
|
||||||
|
assertEquals("test data", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testFullConstructor() {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
HttpRestResult<String> result = new HttpRestResult<>(header, 200, "test data", "message");
|
||||||
|
assertEquals(header, result.getHeader());
|
||||||
|
assertEquals("test data", result.getData());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,81 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.client.handler.BeanResponseHandler;
|
||||||
|
import com.alibaba.nacos.common.http.client.handler.ResponseHandler;
|
||||||
|
import com.alibaba.nacos.common.http.client.handler.RestResultResponseHandler;
|
||||||
|
import com.alibaba.nacos.common.http.client.handler.StringResponseHandler;
|
||||||
|
import com.alibaba.nacos.common.model.RestResult;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class AbstractNacosRestTemplateTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ResponseHandler mockResponseHandler;
|
||||||
|
|
||||||
|
MockNacosRestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
restTemplate = new MockNacosRestTemplate(null);
|
||||||
|
restTemplate.registerResponseHandler(MockNacosRestTemplate.class.getName(), mockResponseHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSelectResponseHandlerForNull() {
|
||||||
|
assertTrue(restTemplate.testFindResponseHandler(null) instanceof StringResponseHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSelectResponseHandlerForRestResult() {
|
||||||
|
assertTrue(restTemplate.testFindResponseHandler(RestResult.class) instanceof RestResultResponseHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSelectResponseHandlerForDefault() {
|
||||||
|
assertTrue(restTemplate
|
||||||
|
.testFindResponseHandler(AbstractNacosRestTemplateTest.class) instanceof BeanResponseHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSelectResponseHandlerForCustom() {
|
||||||
|
assertEquals(mockResponseHandler, restTemplate.testFindResponseHandler(MockNacosRestTemplate.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class MockNacosRestTemplate extends AbstractNacosRestTemplate {
|
||||||
|
|
||||||
|
public MockNacosRestTemplate(Logger logger) {
|
||||||
|
super(logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseHandler testFindResponseHandler(Type responseType) {
|
||||||
|
return super.selectResponseHandler(responseType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class InterceptingHttpClientRequestTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientRequest httpClientRequest;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientRequestInterceptor interceptor;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientResponse interceptorResponse;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientResponse httpClientResponse;
|
||||||
|
|
||||||
|
InterceptingHttpClientRequest clientRequest;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
List<HttpClientRequestInterceptor> interceptorList = new LinkedList<>();
|
||||||
|
interceptorList.add(interceptor);
|
||||||
|
clientRequest = new InterceptingHttpClientRequest(httpClientRequest, interceptorList.listIterator());
|
||||||
|
when(interceptor.intercept()).thenReturn(interceptorResponse);
|
||||||
|
when(httpClientRequest.execute(any(), any(), any())).thenReturn(httpClientResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
clientRequest.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteIntercepted() throws Exception {
|
||||||
|
when(interceptor.isIntercept(any(), any(), any())).thenReturn(true);
|
||||||
|
HttpClientResponse response = clientRequest
|
||||||
|
.execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||||
|
assertEquals(interceptorResponse, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteNotIntercepted() throws Exception {
|
||||||
|
HttpClientResponse response = clientRequest
|
||||||
|
.execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||||
|
assertEquals(httpClientResponse, response);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,176 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||||
|
import com.alibaba.nacos.common.http.Callback;
|
||||||
|
import com.alibaba.nacos.common.http.client.request.AsyncHttpClientRequest;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.MediaType;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class NacosAsyncRestTemplateTest {
|
||||||
|
|
||||||
|
private static final String TEST_URL = "http://127.0.0.1:8848/nacos/test";
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AsyncHttpClientRequest requestClient;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Logger logger;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Callback<String> mockCallback;
|
||||||
|
|
||||||
|
private NacosAsyncRestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
restTemplate = new NacosAsyncRestTemplate(logger, requestClient);
|
||||||
|
when(logger.isDebugEnabled()).thenReturn(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
restTemplate.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGet() throws Exception {
|
||||||
|
restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetWithException() throws Exception {
|
||||||
|
doThrow(new RuntimeException("test")).when(requestClient).execute(any(), any(), any(), any(), any());
|
||||||
|
restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback));
|
||||||
|
verify(mockCallback).onError(any(RuntimeException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetLarge() throws Exception {
|
||||||
|
restTemplate.getLarge(TEST_URL, Header.EMPTY, Query.EMPTY, new Object(), String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("GET-LARGE"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteWithBody() throws Exception {
|
||||||
|
restTemplate.delete(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("DELETE"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteLarge() throws Exception {
|
||||||
|
restTemplate.delete(TEST_URL, Header.EMPTY, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("DELETE_LARGE"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPut() throws Exception {
|
||||||
|
restTemplate.put(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutJson() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.putJson(TEST_URL, header, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutJsonWithQuery() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.putJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutForm() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.putForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutFormWithQuery() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.putForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPost() throws Exception {
|
||||||
|
restTemplate.post(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostJson() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.postJson(TEST_URL, header, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostJsonWithQuery() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.postJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostForm() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.postForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostFormWithQuery() throws Exception {
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
restTemplate.postForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback);
|
||||||
|
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,358 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||||
|
import com.alibaba.nacos.common.http.HttpClientConfig;
|
||||||
|
import com.alibaba.nacos.common.http.HttpRestResult;
|
||||||
|
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.MediaType;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class NacosRestTemplateTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientRequest requestClient;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Logger logger;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientResponse mockResponse;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClientRequestInterceptor interceptor;
|
||||||
|
|
||||||
|
private NacosRestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
restTemplate = new NacosRestTemplate(logger, requestClient);
|
||||||
|
when(logger.isDebugEnabled()).thenReturn(true);
|
||||||
|
when(mockResponse.getHeaders()).thenReturn(Header.EMPTY);
|
||||||
|
when(interceptor.isIntercept(any(), any(), any())).thenReturn(true);
|
||||||
|
when(interceptor.intercept()).thenReturn(mockResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
restTemplate.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetWithDefaultConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetWithCustomConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.get("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetWithInterceptor() throws Exception {
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(300);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test interceptor".getBytes()));
|
||||||
|
restTemplate.setInterceptors(Collections.singletonList(interceptor));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
assertFalse(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test interceptor", result.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = RuntimeException.class)
|
||||||
|
public void testGetWithException() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("GET"), any())).thenThrow(new RuntimeException("test"));
|
||||||
|
restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetLarge() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("GET-LARGE"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.getLarge("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteWithDefaultConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.delete("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteWithCustomConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.delete("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPut() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.put("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutJson() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.putJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutJsonWithQuery() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.putJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutForm() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.putForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutFormWithQuery() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.putForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPutFormWithConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.putForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPost() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.post("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostJson() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.postJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostJsonWithQuery() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.postJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostForm() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.postForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostFormWithQuery() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.postForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testPostFormWithConfig() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.postForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExchangeForm() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.exchangeForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), "PUT",
|
||||||
|
String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
assertEquals(MediaType.APPLICATION_FORM_URLENCODED, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExchange() throws Exception {
|
||||||
|
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||||
|
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||||
|
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||||
|
HttpRestResult<String> result = restTemplate
|
||||||
|
.exchange("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, new Object(), "PUT",
|
||||||
|
String.class);
|
||||||
|
assertTrue(result.ok());
|
||||||
|
assertEquals(Header.EMPTY, result.getHeader());
|
||||||
|
assertEquals("test", result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetInterceptors() {
|
||||||
|
assertTrue(restTemplate.getInterceptors().isEmpty());
|
||||||
|
restTemplate.setInterceptors(Collections.singletonList(interceptor));
|
||||||
|
assertEquals(1, restTemplate.getInterceptors().size());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,57 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.handler;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.HttpRestResult;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
public class BeanResponseHandlerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testConvertResult() throws Exception {
|
||||||
|
List<Integer> testCase = new LinkedList<>();
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
testCase.add(i);
|
||||||
|
}
|
||||||
|
byte[] bytes = JacksonUtils.toJsonBytes(testCase);
|
||||||
|
InputStream inputStream = new ByteArrayInputStream(bytes);
|
||||||
|
HttpClientResponse response = mock(HttpClientResponse.class);
|
||||||
|
when(response.getBody()).thenReturn(inputStream);
|
||||||
|
when(response.getHeaders()).thenReturn(Header.EMPTY);
|
||||||
|
when(response.getStatusCode()).thenReturn(200);
|
||||||
|
BeanResponseHandler<List<Integer>> beanResponseHandler = new BeanResponseHandler<>();
|
||||||
|
beanResponseHandler.setResponseType(List.class);
|
||||||
|
HttpRestResult<List<Integer>> actual = beanResponseHandler.handle(response);
|
||||||
|
assertEquals(200, actual.getCode());
|
||||||
|
assertEquals(testCase, actual.getData());
|
||||||
|
assertNull(actual.getMessage());
|
||||||
|
assertEquals(Header.EMPTY, actual.getHeader());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.handler;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.HttpRestResult;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.model.RestResult;
|
||||||
|
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
public class RestResultResponseHandlerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testConvertResult() throws Exception {
|
||||||
|
RestResult<String> testCase = RestResult.<String>builder().withCode(200).withData("ok").withMsg("msg").build();
|
||||||
|
InputStream inputStream = new ByteArrayInputStream(JacksonUtils.toJsonBytes(testCase));
|
||||||
|
HttpClientResponse response = mock(HttpClientResponse.class);
|
||||||
|
when(response.getBody()).thenReturn(inputStream);
|
||||||
|
when(response.getHeaders()).thenReturn(Header.EMPTY);
|
||||||
|
when(response.getStatusCode()).thenReturn(200);
|
||||||
|
RestResultResponseHandler<String> handler = new RestResultResponseHandler<>();
|
||||||
|
handler.setResponseType(RestResult.class);
|
||||||
|
HttpRestResult<String> actual = handler.handle(response);
|
||||||
|
assertEquals(testCase.getCode(), actual.getCode());
|
||||||
|
assertEquals(testCase.getData(), actual.getData());
|
||||||
|
assertEquals(testCase.getMessage(), actual.getMessage());
|
||||||
|
assertEquals(Header.EMPTY, actual.getHeader());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,161 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.request;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.Callback;
|
||||||
|
import com.alibaba.nacos.common.http.HttpRestResult;
|
||||||
|
import com.alibaba.nacos.common.http.client.handler.ResponseHandler;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.client.config.RequestConfig;
|
||||||
|
import org.apache.http.concurrent.FutureCallback;
|
||||||
|
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
|
||||||
|
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
|
||||||
|
import org.apache.http.impl.nio.reactor.ExceptionEvent;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class DefaultAsyncHttpClientRequestTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CloseableHttpAsyncClient client;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private DefaultConnectingIOReactor ioReactor;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Callback callback;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ResponseHandler responseHandler;
|
||||||
|
|
||||||
|
private RequestConfig defaultConfig;
|
||||||
|
|
||||||
|
DefaultAsyncHttpClientRequest httpClientRequest;
|
||||||
|
|
||||||
|
private URI uri;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
defaultConfig = RequestConfig.DEFAULT;
|
||||||
|
httpClientRequest = new DefaultAsyncHttpClientRequest(client, ioReactor, defaultConfig);
|
||||||
|
uri = URI.create("http://127.0.0.1:8080");
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
httpClientRequest.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteOnFail() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
RuntimeException exception = new RuntimeException("test");
|
||||||
|
when(client.execute(any(), any())).thenAnswer(invocationOnMock -> {
|
||||||
|
((FutureCallback) invocationOnMock.getArgument(1)).failed(exception);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
httpClientRequest.execute(uri, "PUT", httpEntity, responseHandler, callback);
|
||||||
|
verify(callback).onError(exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteOnCancel() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
when(client.execute(any(), any())).thenAnswer(invocationOnMock -> {
|
||||||
|
((FutureCallback) invocationOnMock.getArgument(1)).cancelled();
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
httpClientRequest.execute(uri, "PUT", httpEntity, responseHandler, callback);
|
||||||
|
verify(callback).onCancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteOnComplete() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
HttpResponse response = mock(HttpResponse.class);
|
||||||
|
HttpRestResult restResult = new HttpRestResult();
|
||||||
|
when(responseHandler.handle(any())).thenReturn(restResult);
|
||||||
|
when(client.execute(any(), any())).thenAnswer(invocationOnMock -> {
|
||||||
|
((FutureCallback) invocationOnMock.getArgument(1)).completed(response);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
httpClientRequest.execute(uri, "PUT", httpEntity, responseHandler, callback);
|
||||||
|
verify(callback).onReceive(restResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteOnCompleteWithException() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
HttpResponse response = mock(HttpResponse.class);
|
||||||
|
RuntimeException exception = new RuntimeException("test");
|
||||||
|
when(responseHandler.handle(any())).thenThrow(exception);
|
||||||
|
when(client.execute(any(), any())).thenAnswer(invocationOnMock -> {
|
||||||
|
((FutureCallback) invocationOnMock.getArgument(1)).completed(response);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
httpClientRequest.execute(uri, "PUT", httpEntity, responseHandler, callback);
|
||||||
|
verify(callback).onError(exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteException() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
IllegalStateException exception = new IllegalStateException("test");
|
||||||
|
when(client.execute(any(), any())).thenThrow(exception);
|
||||||
|
when(ioReactor.getAuditLog()).thenReturn(Collections.singletonList(new ExceptionEvent(exception, new Date())));
|
||||||
|
try {
|
||||||
|
httpClientRequest.execute(uri, "PUT", httpEntity, responseHandler, callback);
|
||||||
|
} catch (Exception e) {
|
||||||
|
assertEquals(exception, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,131 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.request;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||||
|
import com.alibaba.nacos.common.http.HttpClientConfig;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.MediaType;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||||
|
import org.apache.http.HttpEntityEnclosingRequest;
|
||||||
|
import org.apache.http.client.config.RequestConfig;
|
||||||
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpRequestBase;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.argThat;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class DefaultHttpClientRequestTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CloseableHttpClient client;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CloseableHttpResponse response;
|
||||||
|
|
||||||
|
private RequestConfig defaultConfig;
|
||||||
|
|
||||||
|
DefaultHttpClientRequest httpClientRequest;
|
||||||
|
|
||||||
|
private boolean isForm;
|
||||||
|
|
||||||
|
private boolean withConfig;
|
||||||
|
|
||||||
|
private URI uri;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
defaultConfig = RequestConfig.DEFAULT;
|
||||||
|
httpClientRequest = new DefaultHttpClientRequest(client, defaultConfig);
|
||||||
|
when(client.execute(argThat(httpUriRequest -> {
|
||||||
|
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpUriRequest;
|
||||||
|
boolean result = isForm == (entityRequest.getEntity() instanceof UrlEncodedFormEntity);
|
||||||
|
HttpRequestBase baseHttpRequest = (HttpRequestBase) httpUriRequest;
|
||||||
|
if (withConfig) {
|
||||||
|
result &= null != baseHttpRequest.getConfig();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}))).thenReturn(response);
|
||||||
|
uri = URI.create("http://127.0.0.1:8080");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
isForm = false;
|
||||||
|
withConfig = false;
|
||||||
|
httpClientRequest.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteForFormWithoutConfig() throws Exception {
|
||||||
|
isForm = true;
|
||||||
|
Header header = Header.newInstance()
|
||||||
|
.addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||||
|
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
|
||||||
|
assertEquals(response, getActualResponse(actual));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteForFormWithConfig() throws Exception {
|
||||||
|
isForm = true;
|
||||||
|
withConfig = true;
|
||||||
|
Header header = Header.newInstance()
|
||||||
|
.addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("test", "test");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(HttpClientConfig.builder().build(), header, Query.EMPTY,
|
||||||
|
body);
|
||||||
|
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
|
||||||
|
assertEquals(response, getActualResponse(actual));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteForOther() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, "body");
|
||||||
|
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
|
||||||
|
assertEquals(response, getActualResponse(actual));
|
||||||
|
}
|
||||||
|
|
||||||
|
private CloseableHttpResponse getActualResponse(HttpClientResponse actual)
|
||||||
|
throws IllegalAccessException, NoSuchFieldException {
|
||||||
|
Field field = actual.getClass().getDeclaredField("response");
|
||||||
|
field.setAccessible(true);
|
||||||
|
return (CloseableHttpResponse) field.get(actual);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,125 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.request;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.http.HttpClientConfig;
|
||||||
|
import com.alibaba.nacos.common.http.HttpUtils;
|
||||||
|
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||||
|
import com.alibaba.nacos.common.http.param.Header;
|
||||||
|
import com.alibaba.nacos.common.http.param.MediaType;
|
||||||
|
import com.alibaba.nacos.common.http.param.Query;
|
||||||
|
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class JdkHttpClientRequestTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpURLConnection connection;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private URI uri;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private URL url;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private OutputStream outputStream;
|
||||||
|
|
||||||
|
JdkHttpClientRequest httpClientRequest;
|
||||||
|
|
||||||
|
private HttpClientConfig httpClientConfig;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
when(uri.toURL()).thenReturn(url);
|
||||||
|
when(url.openConnection()).thenReturn(connection);
|
||||||
|
when(connection.getOutputStream()).thenReturn(outputStream);
|
||||||
|
httpClientConfig = HttpClientConfig.builder().build();
|
||||||
|
httpClientRequest = new JdkHttpClientRequest(httpClientConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
httpClientRequest.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteNormal() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().build();
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, "a=bo&dy");
|
||||||
|
HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity);
|
||||||
|
byte[] writeBytes = "a=bo&dy".getBytes(StandardCharsets.UTF_8);
|
||||||
|
verify(outputStream).write(writeBytes, 0, writeBytes.length);
|
||||||
|
assertEquals(connection, getActualConnection(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteForm() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||||
|
HttpClientConfig config = HttpClientConfig.builder().build();
|
||||||
|
Map<String, String> body = new HashMap<>();
|
||||||
|
body.put("a", "bo&dy");
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, body);
|
||||||
|
HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity);
|
||||||
|
byte[] writeBytes = HttpUtils.encodingParams(body, StandardCharsets.UTF_8.name())
|
||||||
|
.getBytes(StandardCharsets.UTF_8);
|
||||||
|
verify(outputStream).write(writeBytes, 0, writeBytes.length);
|
||||||
|
assertEquals(connection, getActualConnection(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testExecuteEmptyBody() throws Exception {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY);
|
||||||
|
HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity);
|
||||||
|
verify(outputStream, never()).write(any(), eq(0), anyInt());
|
||||||
|
assertEquals(connection, getActualConnection(response));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpURLConnection getActualConnection(HttpClientResponse actual)
|
||||||
|
throws IllegalAccessException, NoSuchFieldException {
|
||||||
|
Field field = actual.getClass().getDeclaredField("conn");
|
||||||
|
field.setAccessible(true);
|
||||||
|
return (HttpURLConnection) field.get(actual);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,100 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.response;
|
||||||
|
|
||||||
|
import org.apache.http.Header;
|
||||||
|
import org.apache.http.HttpEntity;
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.StatusLine;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class DefaultClientHttpResponseTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpResponse response;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private StatusLine statusLine;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpEntity httpEntity;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private InputStream inputStream;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Header header;
|
||||||
|
|
||||||
|
DefaultClientHttpResponse clientHttpResponse;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
when(httpEntity.getContent()).thenReturn(inputStream);
|
||||||
|
when(response.getEntity()).thenReturn(httpEntity);
|
||||||
|
when(response.getStatusLine()).thenReturn(statusLine);
|
||||||
|
when(response.getAllHeaders()).thenReturn(new Header[] {header});
|
||||||
|
when(header.getName()).thenReturn("testName");
|
||||||
|
when(header.getValue()).thenReturn("testValue");
|
||||||
|
clientHttpResponse = new DefaultClientHttpResponse(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
clientHttpResponse.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetStatusCode() {
|
||||||
|
when(statusLine.getStatusCode()).thenReturn(200);
|
||||||
|
assertEquals(200, clientHttpResponse.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetStatusText() {
|
||||||
|
when(statusLine.getReasonPhrase()).thenReturn("test");
|
||||||
|
assertEquals("test", clientHttpResponse.getStatusText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetHeaders() {
|
||||||
|
assertEquals(3, clientHttpResponse.getHeaders().getHeader().size());
|
||||||
|
assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetBody() throws IOException {
|
||||||
|
assertEquals(inputStream, clientHttpResponse.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCloseResponseWithException() {
|
||||||
|
when(response.getEntity()).thenThrow(new RuntimeException("test"));
|
||||||
|
clientHttpResponse.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,99 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.alibaba.nacos.common.http.client.response;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||||
|
import com.alibaba.nacos.common.utils.IoUtils;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class JdkClientHttpResponseTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpURLConnection connection;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private InputStream inputStream;
|
||||||
|
|
||||||
|
private Map<String, List<String>> headers;
|
||||||
|
|
||||||
|
JdkHttpClientResponse clientHttpResponse;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
headers = new HashMap<>();
|
||||||
|
headers.put("testName", Collections.singletonList("testValue"));
|
||||||
|
when(connection.getHeaderFields()).thenReturn(headers);
|
||||||
|
clientHttpResponse = new JdkHttpClientResponse(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
clientHttpResponse.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetStatusCode() throws IOException {
|
||||||
|
when(connection.getResponseCode()).thenReturn(200);
|
||||||
|
assertEquals(200, clientHttpResponse.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetStatusText() throws IOException {
|
||||||
|
when(connection.getResponseMessage()).thenReturn("test");
|
||||||
|
assertEquals("test", clientHttpResponse.getStatusText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetHeaders() {
|
||||||
|
assertEquals(3, clientHttpResponse.getHeaders().getHeader().size());
|
||||||
|
assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetBody() throws IOException {
|
||||||
|
when(connection.getInputStream()).thenReturn(inputStream);
|
||||||
|
assertEquals(inputStream, clientHttpResponse.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetBodyWithGzip() throws IOException {
|
||||||
|
byte[] testCase = IoUtils.tryCompress("test", StandardCharsets.UTF_8.name());
|
||||||
|
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(testCase);
|
||||||
|
when(connection.getInputStream()).thenReturn(byteArrayInputStream);
|
||||||
|
headers.put(HttpHeaderConsts.CONTENT_ENCODING, Collections.singletonList("gzip"));
|
||||||
|
assertEquals("test", IoUtils.toString(clientHttpResponse.getBody(), StandardCharsets.UTF_8.name()));
|
||||||
|
}
|
||||||
|
}
|
@ -1,56 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.alibaba.nacos.common.http.handler;
|
|
||||||
|
|
||||||
import com.alibaba.nacos.common.model.RestResult;
|
|
||||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
|
||||||
import com.alibaba.nacos.common.utils.TypeUtils;
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class ResponseHandlerTest {
|
|
||||||
|
|
||||||
private final ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testDeserializationType() throws Exception {
|
|
||||||
String json = JacksonUtils.toJson(list);
|
|
||||||
ArrayList<Integer> tmp = ResponseHandler.convert(json, TypeUtils.parameterize(List.class, Integer.class));
|
|
||||||
Assert.assertEquals(list, tmp);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testRestResult() throws Exception {
|
|
||||||
String json = "{\"code\":200,\"message\":null,\"data\":[{\"USERNAME\":\"nacos\",\"PASSWORD\":"
|
|
||||||
+ "\"$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu\",\"ENABLED\":true}]}";
|
|
||||||
RestResult<Object> result = ResponseHandler.convert(json, TypeUtils.parameterize(RestResult.class, Object.class));
|
|
||||||
Assert.assertEquals(200, result.getCode());
|
|
||||||
Assert.assertNull(result.getMessage());
|
|
||||||
Assert.assertNotNull(result.getData());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testDeserializationClass() throws Exception {
|
|
||||||
String json = JacksonUtils.toJson(list);
|
|
||||||
ArrayList<Integer> tmp = ResponseHandler.convert(json, TypeUtils.parameterize(List.class, Integer.class));
|
|
||||||
Assert.assertEquals(list, tmp);
|
|
||||||
}
|
|
||||||
}
|
|
@ -16,16 +16,122 @@
|
|||||||
|
|
||||||
package com.alibaba.nacos.common.http.param;
|
package com.alibaba.nacos.common.http.param;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class HeaderTest {
|
public class HeaderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSetContentType() {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.setContentType(null);
|
||||||
|
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
header.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||||
|
assertEquals(MediaType.MULTIPART_FORM_DATA, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testHeaderKyeIgnoreCase() {
|
public void testHeaderKyeIgnoreCase() {
|
||||||
Header header = Header.newInstance();
|
Header header = Header.newInstance();
|
||||||
header.addParam("Content-Encoding", "gzip");
|
header.addParam("Content-Encoding", "gzip");
|
||||||
assertEquals("gzip", header.getValue("content-encoding"));
|
assertEquals("gzip", header.getValue("content-encoding"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testToList() {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
List<String> list = header.toList();
|
||||||
|
assertTrue(list.contains(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
assertTrue(list.contains(MediaType.APPLICATION_JSON));
|
||||||
|
assertEquals(1, list.indexOf(MediaType.APPLICATION_JSON) - list.indexOf(HttpHeaderConsts.CONTENT_TYPE));
|
||||||
|
assertTrue(list.contains(HttpHeaderConsts.ACCEPT_CHARSET));
|
||||||
|
assertTrue(list.contains("UTF-8"));
|
||||||
|
assertEquals(1, list.indexOf("UTF-8") - list.indexOf(HttpHeaderConsts.ACCEPT_CHARSET));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddAllForMap() {
|
||||||
|
Map<String, String> map = new HashMap<>();
|
||||||
|
map.put("test1", "test2");
|
||||||
|
map.put("test3", "test4");
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.addAll(map);
|
||||||
|
assertEquals("test2", header.getValue("test1"));
|
||||||
|
assertEquals("test4", header.getValue("test3"));
|
||||||
|
assertEquals(4, header.getHeader().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddAllForList() {
|
||||||
|
List<String> list = new ArrayList<>(4);
|
||||||
|
list.add("test1");
|
||||||
|
list.add("test2");
|
||||||
|
list.add("test3");
|
||||||
|
list.add("test4");
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.addAll(list);
|
||||||
|
assertEquals("test2", header.getValue("test1"));
|
||||||
|
assertEquals("test4", header.getValue("test3"));
|
||||||
|
assertEquals(4, header.getHeader().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void testAddAllForListWithWrongLength() {
|
||||||
|
List<String> list = new ArrayList<>(3);
|
||||||
|
list.add("test1");
|
||||||
|
list.add("test2");
|
||||||
|
list.add("test3");
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.addAll(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddOriginalResponseHeader() {
|
||||||
|
List<String> list = new ArrayList<>(4);
|
||||||
|
list.add("test1");
|
||||||
|
list.add("test2");
|
||||||
|
list.add("test3");
|
||||||
|
list.add("test4");
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.addOriginalResponseHeader("test", list);
|
||||||
|
assertEquals("test1", header.getValue("test"));
|
||||||
|
assertEquals(1, header.getOriginalResponseHeader().size());
|
||||||
|
assertEquals(list, header.getOriginalResponseHeader().get("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetCharset() {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
assertEquals("UTF-8", header.getCharset());
|
||||||
|
header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, null);
|
||||||
|
header.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
assertEquals("UTF-8", header.getCharset());
|
||||||
|
header.setContentType("application/json;charset=GBK");
|
||||||
|
assertEquals("GBK", header.getCharset());
|
||||||
|
header.setContentType("application/json");
|
||||||
|
assertEquals("UTF-8", header.getCharset());
|
||||||
|
header.setContentType("");
|
||||||
|
assertEquals("UTF-8", header.getCharset());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testClear() {
|
||||||
|
Header header = Header.newInstance();
|
||||||
|
header.addOriginalResponseHeader("test", Collections.singletonList("test"));
|
||||||
|
assertEquals(3, header.getHeader().size());
|
||||||
|
assertEquals(1, header.getOriginalResponseHeader().size());
|
||||||
|
header.clear();
|
||||||
|
assertEquals(0, header.getHeader().size());
|
||||||
|
assertEquals(0, header.getOriginalResponseHeader().size());
|
||||||
|
assertEquals("Header{headerToMap={}}", header.toString());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,4 +59,13 @@ public class MediaTypeTest {
|
|||||||
assertEquals(excepted, mediaType.toString());
|
assertEquals(excepted, mediaType.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void testValueOfWithEmpty() {
|
||||||
|
MediaType.valueOf("");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void testValueOfWithEmpty2() {
|
||||||
|
MediaType.valueOf("", "UTF-8");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,6 @@
|
|||||||
package com.alibaba.nacos.common.http.param;
|
package com.alibaba.nacos.common.http.param;
|
||||||
|
|
||||||
import com.alibaba.nacos.api.naming.CommonParams;
|
import com.alibaba.nacos.api.naming.CommonParams;
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
@ -26,11 +25,13 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class QueryTest {
|
public class QueryTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testToQueryUrl() {
|
public void testInitParams() {
|
||||||
Map<String, String> parameters = new LinkedHashMap<String, String>();
|
Map<String, String> parameters = new LinkedHashMap<String, String>();
|
||||||
parameters.put(CommonParams.NAMESPACE_ID, "namespace");
|
parameters.put(CommonParams.NAMESPACE_ID, "namespace");
|
||||||
parameters.put(CommonParams.SERVICE_NAME, "service");
|
parameters.put(CommonParams.SERVICE_NAME, "service");
|
||||||
@ -41,16 +42,27 @@ public class QueryTest {
|
|||||||
parameters.put("weight", String.valueOf(1.0));
|
parameters.put("weight", String.valueOf(1.0));
|
||||||
parameters.put("ephemeral", String.valueOf(true));
|
parameters.put("ephemeral", String.valueOf(true));
|
||||||
String excepted = "namespaceId=namespace&serviceName=service&groupName=group&ip=1.1.1.1&port=9999&weight=1.0&ephemeral=true";
|
String excepted = "namespaceId=namespace&serviceName=service&groupName=group&ip=1.1.1.1&port=9999&weight=1.0&ephemeral=true";
|
||||||
assertEquals(excepted, Query.newInstance().initParams(parameters).toQueryUrl());
|
Query actual = Query.newInstance().initParams(parameters);
|
||||||
|
assertEquals(excepted, actual.toQueryUrl());
|
||||||
|
assertEquals("namespace", actual.getValue(CommonParams.NAMESPACE_ID));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testToQueryUrl2() throws Exception {
|
public void testAddParams() throws Exception {
|
||||||
Query query = Query.newInstance().addParam("key-1", "value-1")
|
Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2");
|
||||||
.addParam("key-2", "value-2");
|
|
||||||
String s1 = query.toQueryUrl();
|
String s1 = query.toQueryUrl();
|
||||||
String s2 = "key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name())
|
String s2 = "key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name()) + "&key-2=" + URLEncoder
|
||||||
+ "&key-2=" + URLEncoder.encode("value-2", StandardCharsets.UTF_8.name());
|
.encode("value-2", StandardCharsets.UTF_8.name());
|
||||||
Assert.assertEquals(s1, s2);
|
assertEquals(s2, s1);
|
||||||
|
assertEquals("value-1", query.getValue("key-1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testClear() {
|
||||||
|
Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2");
|
||||||
|
assertFalse(query.isEmpty());
|
||||||
|
assertEquals("value-1", query.getValue("key-1"));
|
||||||
|
query.clear();
|
||||||
|
assertTrue(query.isEmpty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -67,7 +67,7 @@ public final class HttpClientManager {
|
|||||||
LOGGER.warn("[ConfigServer-HttpClientManager] Start destroying NacosRestTemplate");
|
LOGGER.warn("[ConfigServer-HttpClientManager] Start destroying NacosRestTemplate");
|
||||||
try {
|
try {
|
||||||
final String httpClientFactoryBeanName = ConfigHttpClientFactory.class.getName();
|
final String httpClientFactoryBeanName = ConfigHttpClientFactory.class.getName();
|
||||||
HttpClientBeanHolder.shutdownNacostSyncRest(httpClientFactoryBeanName);
|
HttpClientBeanHolder.shutdownNacosSyncRest(httpClientFactoryBeanName);
|
||||||
HttpClientBeanHolder.shutdownNacosAsyncRest(httpClientFactoryBeanName);
|
HttpClientBeanHolder.shutdownNacosAsyncRest(httpClientFactoryBeanName);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
LOGGER.error("[ConfigServer-HttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
LOGGER.error("[ConfigServer-HttpClientManager] An exception occurred when the HTTP client was closed : {}",
|
||||||
|
@ -106,8 +106,8 @@ public class HttpClientManager {
|
|||||||
private static void shutdown() {
|
private static void shutdown() {
|
||||||
SRV_LOG.warn("[NamingServerHttpClientManager] Start destroying HTTP-Client");
|
SRV_LOG.warn("[NamingServerHttpClientManager] Start destroying HTTP-Client");
|
||||||
try {
|
try {
|
||||||
HttpClientBeanHolder.shutdownNacostSyncRest(SYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosSyncRest(SYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
HttpClientBeanHolder.shutdownNacostSyncRest(APACHE_SYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosSyncRest(APACHE_SYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
HttpClientBeanHolder.shutdownNacosAsyncRest(ASYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosAsyncRest(ASYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
HttpClientBeanHolder.shutdownNacosAsyncRest(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
HttpClientBeanHolder.shutdownNacosAsyncRest(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY.getClass().getName());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
|
Loading…
Reference in New Issue
Block a user