Skip to content

Commit

Permalink
Develop fill ut common (#11419)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
KomachiSion authored Nov 23, 2023
1 parent 15c48f4 commit 7ce1774
Show file tree
Hide file tree
Showing 33 changed files with 2,105 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public static ConfigHttpClientManager getInstance() {
public void shutdown() throws NacosException {
NAMING_LOGGER.warn("[ConfigHttpClientManager] Start destroying NacosRestTemplate");
try {
HttpClientBeanHolder.shutdownNacostSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
HttpClientBeanHolder.shutdownNacosSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
} catch (Exception ex) {
NAMING_LOGGER.error("[ConfigHttpClientManager] An exception occurred when the HTTP client was closed : {}",
ExceptionUtil.getStackTrace(ex));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public NacosRestTemplate getNacosRestTemplate() {
public void shutdown() throws NacosException {
NAMING_LOGGER.warn("[NamingHttpClientManager] Start destroying NacosRestTemplate");
try {
HttpClientBeanHolder.shutdownNacostSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
HttpClientBeanHolder.shutdownNacosSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
} catch (Exception ex) {
NAMING_LOGGER.error("[NamingHttpClientManager] An exception occurred when the HTTP client was closed : {}",
ExceptionUtil.getStackTrace(ex));
Expand Down
12 changes: 12 additions & 0 deletions common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</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>
<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,6 @@ protected void initTls(BiConsumer<SSLContext, HostnameVerifier> initTlsBiFunc,

@SuppressWarnings("checkstyle:abbreviationaswordinname")
protected synchronized SSLContext loadSSLContext() {
if (!TlsSystemConfig.tlsEnable) {
return null;
}
try {
return TlsHelper.buildSslContext(true);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ private static void shutdown() {
* @throws Exception ex
*/
public static void shutdown(String className) throws Exception {
shutdownNacostSyncRest(className);
shutdownNacosSyncRest(className);
shutdownNacosAsyncRest(className);
}

Expand All @@ -128,7 +128,7 @@ public static void shutdown(String className) throws Exception {
* @param className HttpClientFactory implement class name
* @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);
if (nacosRestTemplate != null) {
nacosRestTemplate.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,6 @@ public InputStream getBody() throws IOException {
// Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream
if (CONTENT_ENCODING.equals(contentEncoding)) {
byte[] bytes = IoUtils.tryDecompress(this.responseStream);
if (bytes == null) {
throw new IOException("decompress http response error");
}
return new ByteArrayInputStream(bytes);
}
return this.responseStream;
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -42,24 +42,21 @@ public class Header {

private static final String DEFAULT_CHARSET = "UTF-8";

private static final String DEFAULT_ENCODING = "gzip";

private Header() {
header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_JSON);
addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET);
//addParam(HttpHeaderConsts.ACCEPT_ENCODING, DEFAULT_ENCODING);
}

public static Header newInstance() {
return new Header();
}

/**
* Add the key and value to the header.
*
* @param key the key
* @param key the key
* @param value the value
* @return header
*/
Expand All @@ -77,10 +74,6 @@ public Header setContentType(String contentType) {
return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType);
}

public Header build() {
return this;
}

public String getValue(String key) {
return header.get(key);
}
Expand Down Expand Up @@ -146,7 +139,7 @@ public void addAll(Map<String, String> params) {
*
* <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
*/
public void addOriginalResponseHeader(String key, List<String> values) {
Expand Down Expand Up @@ -179,7 +172,7 @@ public String getCharset() {
private String analysisCharset(String contentType) {
String[] values = contentType.split(";");
String charset = Constants.ENCODE;
if (values.length == 0) {
if (values.length == 1) {
return charset;
}
for (String value : values) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

Expand Down Expand Up @@ -80,20 +79,6 @@ public Query initParams(Map<String, String> params) {
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.
*
Expand Down Expand Up @@ -122,8 +107,8 @@ public String toQueryUrl() {
}

public void clear() {
isEmpty = false;
params.clear();
isEmpty = true;
}

public boolean isEmpty() {
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading

0 comments on commit 7ce1774

Please sign in to comment.