Develop fill ut common (#11335)
* Add UT for common module utils * Add UT for common module utils package. * For checkstyle. * For checkstyle.
This commit is contained in:
parent
cc656e19d3
commit
0d46af03b7
@ -17,7 +17,7 @@
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.packagescan.util.PathMatcher;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
|
@ -16,8 +16,8 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractObjectUtils;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractObjectUtils;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.ClassUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
|
@ -17,7 +17,7 @@
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.packagescan.util.ResourceUtils;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.ClassUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
@ -18,7 +18,7 @@ package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.packagescan.util.PathMatcher;
|
||||
import com.alibaba.nacos.common.packagescan.util.ResourceUtils;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.ClassUtils;
|
||||
import com.alibaba.nacos.common.utils.ReflectUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
|
@ -17,7 +17,7 @@
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.packagescan.util.ResourceUtils;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.packagescan.resource;
|
||||
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.AbstractAssert;
|
||||
import com.alibaba.nacos.common.packagescan.util.NestedIoException;
|
||||
|
||||
import java.io.File;
|
||||
|
@ -1,11 +1,11 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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,
|
||||
@ -14,7 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
package com.alibaba.nacos.common.packagescan.util;
|
||||
|
||||
import com.alibaba.nacos.common.utils.CollectionUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
@ -1,11 +1,11 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* 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
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* 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,
|
||||
@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
package com.alibaba.nacos.common.packagescan.util;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
@ -17,7 +17,6 @@
|
||||
package com.alibaba.nacos.common.packagescan.util;
|
||||
|
||||
import com.alibaba.nacos.common.packagescan.resource.Resource;
|
||||
import com.alibaba.nacos.common.utils.AbstractAssert;
|
||||
import com.alibaba.nacos.common.utils.ClassUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
|
@ -43,7 +43,7 @@ import static com.alibaba.nacos.api.exception.NacosException.SERVER_ERROR;
|
||||
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
|
||||
*/
|
||||
public final class ClassUtils {
|
||||
|
||||
|
||||
private ClassUtils() {
|
||||
}
|
||||
|
||||
@ -241,7 +241,7 @@ public final class ClassUtils {
|
||||
*/
|
||||
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
|
||||
|
||||
AbstractAssert.notNull(name, "Name must not be null");
|
||||
Objects.requireNonNull(name, "Name must not be null");
|
||||
|
||||
Class<?> clazz = resolvePrimitiveClassName(name);
|
||||
if (clazz == null) {
|
||||
@ -386,7 +386,7 @@ public final class ClassUtils {
|
||||
* @return the corresponding resource path, pointing to the class
|
||||
*/
|
||||
public static String convertClassNameToResourcePath(String className) {
|
||||
AbstractAssert.notNull(className, "Class name must not be null");
|
||||
Objects.requireNonNull(className, "Class name must not be null");
|
||||
return className.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
|
||||
}
|
||||
|
||||
@ -397,7 +397,7 @@ public final class ClassUtils {
|
||||
* @return the corresponding resource path, pointing to the class
|
||||
*/
|
||||
public static String resourcePathToConvertClassName(String className) {
|
||||
AbstractAssert.notNull(className, "Class name must not be null");
|
||||
Objects.requireNonNull(className, "Class name must not be null");
|
||||
return className.replace(PATH_SEPARATOR, PACKAGE_SEPARATOR);
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,10 @@
|
||||
/**
|
||||
* Copyright 2018-2021 Dynatrace LLC
|
||||
* 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.
|
||||
* Copyright 2018-2021 Dynatrace LLC 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.utils;
|
||||
@ -22,7 +18,7 @@ import java.util.regex.Pattern;
|
||||
*/
|
||||
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName", "PMD.ClassNamingShouldBeCamelRule"})
|
||||
public class InetAddressValidator {
|
||||
|
||||
|
||||
private InetAddressValidator() {
|
||||
}
|
||||
|
||||
@ -59,9 +55,8 @@ public class InetAddressValidator {
|
||||
.compile("^" + "(?:[0-9a-fA-F]{1,4}:){6}" + "$");
|
||||
|
||||
/**
|
||||
* Check if <code>input</code> is a valid IPv4 address.
|
||||
* The format is 'xxx.xxx.xxx.xxx'. Four blocks of integer numbers ranging from 0 to 255
|
||||
* are required. Letters are not allowed.
|
||||
* Check if <code>input</code> is a valid IPv4 address. The format is 'xxx.xxx.xxx.xxx'. Four blocks of integer
|
||||
* numbers ranging from 0 to 255 are required. Letters are not allowed.
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv4 notation.
|
||||
@ -71,9 +66,8 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given address is a valid IPv6 address in the standard format
|
||||
* The format is 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. Eight blocks of hexadecimal digits
|
||||
* are required.
|
||||
* Check if the given address is a valid IPv6 address in the standard format The format is
|
||||
* 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. Eight blocks of hexadecimal digits are required.
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv6 notation.
|
||||
@ -83,9 +77,8 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given address is a valid IPv6 address in the hex-compressed notation
|
||||
* The format is 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. If all digits in a block are '0'
|
||||
* the block can be left empty.
|
||||
* Check if the given address is a valid IPv6 address in the hex-compressed notation The format is
|
||||
* 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. If all digits in a block are '0' the block can be left empty.
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv6 (hex-compressed) notation.
|
||||
@ -95,13 +88,8 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if <code>input</code> is a IPv6 address.
|
||||
* Possible notations for valid IPv6 are:
|
||||
* - Standard IPv6 address
|
||||
* - Hex-compressed IPv6 address
|
||||
* - Link-local IPv6 address
|
||||
* - IPv4-mapped-to-IPV6 address
|
||||
* - IPv6 mixed address
|
||||
* Check if <code>input</code> is a IPv6 address. Possible notations for valid IPv6 are: - Standard IPv6 address -
|
||||
* Hex-compressed IPv6 address - Link-local IPv6 address - IPv4-mapped-to-IPV6 address - IPv6 mixed address
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv6 notation.
|
||||
@ -112,11 +100,9 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given address is a valid IPv6 address in the mixed-standard or mixed-compressed notation.
|
||||
* IPV6 Mixed mode consists of two parts, the first 96 bits (up to 6 blocks of 4 hex digits) are IPv6
|
||||
* the IPV6 part can be either compressed or uncompressed
|
||||
* the second block is a full IPv4 address
|
||||
* e.g. '0:0:0:0:0:0:172.12.55.18'
|
||||
* Check if the given address is a valid IPv6 address in the mixed-standard or mixed-compressed notation. IPV6 Mixed
|
||||
* mode consists of two parts, the first 96 bits (up to 6 blocks of 4 hex digits) are IPv6 the IPV6 part can be
|
||||
* either compressed or uncompressed the second block is a full IPv4 address e.g. '0:0:0:0:0:0:172.12.55.18'
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv6 (mixed-standard or mixed-compressed) notation.
|
||||
@ -143,9 +129,8 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if <code>input</code> is an IPv4 address mapped into a IPv6 address. These are
|
||||
* starting with "::ffff:" followed by the IPv4 address in a dot-seperated notation.
|
||||
* The format is '::ffff:d.d.d.d'
|
||||
* Check if <code>input</code> is an IPv4 address mapped into a IPv6 address. These are starting with "::ffff:"
|
||||
* followed by the IPv4 address in a dot-seperated notation. The format is '::ffff:d.d.d.d'
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if <code>input</code> is in correct IPv6 notation containing an IPv4 address
|
||||
@ -159,8 +144,8 @@ public class InetAddressValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if <code>input</code> is a link local IPv6 address starting with "fe80:" and containing
|
||||
* a zone index with "%xxx". The zone index will not be checked.
|
||||
* Check if <code>input</code> is a link local IPv6 address starting with "fe80:" and containing a zone index with
|
||||
* "%xxx". The zone index will not be checked.
|
||||
*
|
||||
* @param input ip-address to check
|
||||
* @return true if address part of <code>input</code> is in correct IPv6 notation.
|
||||
@ -176,27 +161,4 @@ public class InetAddressValidator {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if <code>input</code> is a valid IPv4 or IPv6 address.
|
||||
*
|
||||
* @param ipAddress ip-address to check
|
||||
* @return <code>true</code> if <code>ipAddress</code> is a valid ip-address
|
||||
*/
|
||||
public static boolean isValidIP(String ipAddress) {
|
||||
if (ipAddress == null || ipAddress.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isIPv4Address(ipAddress) || isIPv6Address(ipAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* get to ipv4 pattern.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static Pattern getIpv4Pattern() {
|
||||
return IPV4_PATTERN;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -24,7 +24,6 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.CharArrayWriter;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@ -33,7 +32,6 @@ import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@ -46,7 +44,7 @@ import java.util.zip.GZIPOutputStream;
|
||||
* @author nacos
|
||||
*/
|
||||
public class IoUtils {
|
||||
|
||||
|
||||
private IoUtils() {
|
||||
}
|
||||
|
||||
@ -75,11 +73,7 @@ public class IoUtils {
|
||||
if (!isGzipStream(raw)) {
|
||||
return raw;
|
||||
}
|
||||
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(raw));
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
copy(gis, out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
return tryDecompress(new ByteArrayInputStream(raw));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -276,31 +270,6 @@ public class IoUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy File.
|
||||
*
|
||||
* @param source source file path
|
||||
* @param target target file path
|
||||
* @throws IOException io exception
|
||||
*/
|
||||
public static void copyFile(String source, String target) throws IOException {
|
||||
File sf = new File(source);
|
||||
if (!sf.exists()) {
|
||||
throw new IllegalArgumentException("source file does not exist.");
|
||||
}
|
||||
File tf = new File(target);
|
||||
if (!tf.getParentFile().mkdirs()) {
|
||||
throw new RuntimeException("failed to create parent directory.");
|
||||
}
|
||||
if (!tf.exists() && !tf.createNewFile()) {
|
||||
throw new RuntimeException("failed to create target file.");
|
||||
}
|
||||
try (FileChannel sc = new FileInputStream(sf).getChannel();
|
||||
FileChannel tc = new FileOutputStream(tf).getChannel()) {
|
||||
sc.transferTo(0, sc.size(), tc);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Judge whether is Gzip stream.
|
||||
*
|
||||
|
@ -16,9 +16,6 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
@ -26,7 +23,6 @@ import java.util.Collection;
|
||||
import java.util.Deque;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
/**
|
||||
@ -36,7 +32,7 @@ import java.util.StringTokenizer;
|
||||
* @author zzq
|
||||
*/
|
||||
public class StringUtils {
|
||||
|
||||
|
||||
private StringUtils() {
|
||||
}
|
||||
|
||||
@ -226,108 +222,6 @@ public class StringUtils {
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
public static String escapeJavaScript(String str) {
|
||||
return escapeJavaStyleString(str, true, true);
|
||||
}
|
||||
|
||||
private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
StringWriter writer = new StringWriter(str.length() * 2);
|
||||
escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash);
|
||||
return writer.toString();
|
||||
} catch (IOException ioe) {
|
||||
// this should never ever happen while writing to a StringWriter
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote,
|
||||
boolean escapeForwardSlash) throws IOException {
|
||||
if (out == null) {
|
||||
throw new IllegalArgumentException("The Writer must not be null");
|
||||
}
|
||||
if (str == null) {
|
||||
return;
|
||||
}
|
||||
int sz;
|
||||
sz = str.length();
|
||||
for (int i = 0; i < sz; i++) {
|
||||
char ch = str.charAt(i);
|
||||
|
||||
// handle unicode
|
||||
if (ch > 0xfff) {
|
||||
out.write("\\u" + hex(ch));
|
||||
} else if (ch > 0xff) {
|
||||
out.write("\\u0" + hex(ch));
|
||||
} else if (ch > 0x7f) {
|
||||
out.write("\\u00" + hex(ch));
|
||||
} else if (ch < 32) {
|
||||
switch (ch) {
|
||||
case '\b':
|
||||
out.write('\\');
|
||||
out.write('b');
|
||||
break;
|
||||
case '\n':
|
||||
out.write('\\');
|
||||
out.write('n');
|
||||
break;
|
||||
case '\t':
|
||||
out.write('\\');
|
||||
out.write('t');
|
||||
break;
|
||||
case '\f':
|
||||
out.write('\\');
|
||||
out.write('f');
|
||||
break;
|
||||
case '\r':
|
||||
out.write('\\');
|
||||
out.write('r');
|
||||
break;
|
||||
default:
|
||||
if (ch > 0xf) {
|
||||
out.write("\\u00" + hex(ch));
|
||||
} else {
|
||||
out.write("\\u000" + hex(ch));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (ch) {
|
||||
case '\'':
|
||||
if (escapeSingleQuote) {
|
||||
out.write('\\');
|
||||
}
|
||||
out.write('\'');
|
||||
break;
|
||||
case '"':
|
||||
out.write('\\');
|
||||
out.write('"');
|
||||
break;
|
||||
case '\\':
|
||||
out.write('\\');
|
||||
out.write('\\');
|
||||
break;
|
||||
case '/':
|
||||
if (escapeForwardSlash) {
|
||||
out.write('\\');
|
||||
}
|
||||
out.write('/');
|
||||
break;
|
||||
default:
|
||||
out.write(ch);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String hex(char ch) {
|
||||
return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if CharSequence contains a search CharSequence irrespective of case, handling {@code null}.
|
||||
* Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}.
|
||||
@ -503,10 +397,6 @@ public class StringUtils {
|
||||
return str.split(separatorChars);
|
||||
}
|
||||
|
||||
private static String[] tokenizeLocaleSource(String localeSource) {
|
||||
return tokenizeToStringArray(localeSource, "_ ", false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenize the given {@code String} into a {@code String} array via a {@link StringTokenizer}.
|
||||
*
|
||||
@ -899,21 +789,17 @@ public class StringUtils {
|
||||
* @return the capitalized {@code String}
|
||||
*/
|
||||
public static String capitalize(String str) {
|
||||
return changeFirstCharacterCase(str, true);
|
||||
return changeFirstCharacterCase(str);
|
||||
}
|
||||
|
||||
private static String changeFirstCharacterCase(String str, boolean capitalize) {
|
||||
private static String changeFirstCharacterCase(String str) {
|
||||
if (!hasLength(str)) {
|
||||
return str;
|
||||
}
|
||||
|
||||
char baseChar = str.charAt(0);
|
||||
char updatedChar;
|
||||
if (capitalize) {
|
||||
updatedChar = Character.toUpperCase(baseChar);
|
||||
} else {
|
||||
updatedChar = Character.toLowerCase(baseChar);
|
||||
}
|
||||
updatedChar = Character.toUpperCase(baseChar);
|
||||
if (baseChar == updatedChar) {
|
||||
return str;
|
||||
}
|
||||
|
@ -29,25 +29,12 @@ import java.util.concurrent.TimeUnit;
|
||||
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
|
||||
*/
|
||||
public final class ThreadUtils {
|
||||
|
||||
|
||||
private ThreadUtils() {
|
||||
}
|
||||
|
||||
private static final int THREAD_MULTIPLER = 2;
|
||||
|
||||
/**
|
||||
* Wait.
|
||||
*
|
||||
* @param object load object
|
||||
*/
|
||||
public static void objectWait(Object object) {
|
||||
try {
|
||||
object.wait();
|
||||
} catch (InterruptedException ignore) {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep.
|
||||
*
|
||||
|
18
common/src/test/java/ClassUtilsTestMockClass.java
Normal file
18
common/src/test/java/ClassUtilsTestMockClass.java
Normal file
@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
public class ClassUtilsTestMockClass {
|
||||
}
|
@ -1,122 +0,0 @@
|
||||
/*
|
||||
* Copyright 1999-2022 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.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertThrows;
|
||||
|
||||
public class AbstractAssertTest {
|
||||
|
||||
@Test
|
||||
public void testState() {
|
||||
assertThrows("error message", IllegalStateException.class, () -> AbstractAssert.state(false, "error message"));
|
||||
assertThrows("error", IllegalStateException.class, () -> AbstractAssert.state(false, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsTrue() {
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isTrue(false, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isTrue(false, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsNull() {
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isNull(new Object(), "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isNull(new Object(), () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotNull() {
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notNull(null, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notNull(null, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasLength() {
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasLength(null, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasLength(null, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasText() {
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasText(null, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasText(null, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotContain() {
|
||||
assertThrows(IllegalArgumentException.class, () -> AbstractAssert.doesNotContain("abcd", "bc"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.doesNotContain("abcd", "bc", () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEmpty() {
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.notEmpty(Collections.EMPTY_MAP, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.notEmpty(Collections.EMPTY_MAP, () -> "error"));
|
||||
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notEmpty(new Object[] {}, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.notEmpty(new Object[] {}, () -> "error"));
|
||||
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.notEmpty(Collections.emptyList(), "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.notEmpty(Collections.emptyList(), () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoNullElements() {
|
||||
List<String> list = new LinkedList<>();
|
||||
list.add(null);
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(list, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(list, () -> "error"));
|
||||
|
||||
Object[] objects = new Object[1];
|
||||
assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(objects, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.noNullElements(objects, () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsInstanceOf() {
|
||||
assertThrows("", IllegalArgumentException.class, () -> AbstractAssert.isInstanceOf(String.class, new Object()));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.isInstanceOf(String.class, new Object(), "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.isInstanceOf(String.class, new Object(), () -> "error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsAssignable() {
|
||||
assertThrows("", IllegalArgumentException.class, () -> AbstractAssert.isAssignable(String.class, null));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.isAssignable(String.class, null, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.isAssignable(String.class, Integer.class, "error"));
|
||||
assertThrows("error", IllegalArgumentException.class,
|
||||
() -> AbstractAssert.isAssignable(String.class, Integer.class, () -> "error"));
|
||||
}
|
||||
|
||||
}
|
@ -1,203 +0,0 @@
|
||||
/*
|
||||
* Copyright 1999-2022 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.utils;
|
||||
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class AbstractObjectUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testIsCheckedException() {
|
||||
assertTrue(AbstractObjectUtils.isCheckedException(new NacosException()));
|
||||
assertFalse(AbstractObjectUtils.isCheckedException(new RuntimeException()));
|
||||
assertFalse(AbstractObjectUtils.isCheckedException(new Error()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsCompatibleWithThrowsClause() {
|
||||
assertTrue(AbstractObjectUtils.isCompatibleWithThrowsClause(new NacosException(), Exception.class));
|
||||
assertFalse(AbstractObjectUtils.isCompatibleWithThrowsClause(new NacosException(), RuntimeException.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsArray() {
|
||||
assertTrue(AbstractObjectUtils.isArray(new Object[] {}));
|
||||
assertFalse(AbstractObjectUtils.isArray(new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmpty() {
|
||||
assertTrue(AbstractObjectUtils.isEmpty(null));
|
||||
|
||||
assertTrue(AbstractObjectUtils.isEmpty(Optional.empty()));
|
||||
assertFalse(AbstractObjectUtils.isEmpty(Optional.of("1")));
|
||||
|
||||
assertTrue(AbstractObjectUtils.isEmpty(""));
|
||||
assertFalse(AbstractObjectUtils.isEmpty("1"));
|
||||
|
||||
assertTrue(AbstractObjectUtils.isEmpty(Collections.EMPTY_LIST));
|
||||
assertFalse(AbstractObjectUtils.isEmpty(Arrays.asList(1, 2)));
|
||||
|
||||
assertTrue(AbstractObjectUtils.isEmpty(Collections.EMPTY_MAP));
|
||||
assertFalse(AbstractObjectUtils.isEmpty(new HashMap<String, String>() {
|
||||
{
|
||||
put("k", "v");
|
||||
}
|
||||
}));
|
||||
|
||||
assertFalse(AbstractObjectUtils.isEmpty(new Object()));
|
||||
|
||||
assertTrue(AbstractObjectUtils.isEmpty(new Object[] {}));
|
||||
assertFalse(AbstractObjectUtils.isEmpty(new Object[] {""}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnwrapOptional() {
|
||||
Object o = new Object();
|
||||
assertNull(AbstractObjectUtils.unwrapOptional(null));
|
||||
assertNull(AbstractObjectUtils.unwrapOptional(Optional.empty()));
|
||||
assertEquals(o, AbstractObjectUtils.unwrapOptional(Optional.of(o)));
|
||||
assertEquals(o, AbstractObjectUtils.unwrapOptional(o));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContainsElement() {
|
||||
Object[] objects = new Object[] {1, 2, 3};
|
||||
assertTrue(AbstractObjectUtils.containsElement(objects, 1));
|
||||
assertFalse(AbstractObjectUtils.containsElement(objects, 4));
|
||||
assertFalse(AbstractObjectUtils.containsElement(null, 1));
|
||||
}
|
||||
|
||||
private enum ETest {
|
||||
CASE1,
|
||||
CASE2
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContainsConstant() {
|
||||
assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "case1"));
|
||||
assertFalse(AbstractObjectUtils.containsConstant(ETest.values(), "case3"));
|
||||
|
||||
assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "CASE1", true));
|
||||
assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "CASE1", false));
|
||||
assertFalse(AbstractObjectUtils.containsConstant(ETest.values(), "case1", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCaseInsensitiveValueOf() {
|
||||
assertEquals(ETest.CASE1, AbstractObjectUtils.caseInsensitiveValueOf(ETest.values(), "case1"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AbstractObjectUtils.caseInsensitiveValueOf(ETest.values(), "3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddObjectToArray() {
|
||||
Object[] objects = new Object[0];
|
||||
Object[] objects1 = AbstractObjectUtils.addObjectToArray(objects, 1);
|
||||
assertEquals(1, objects1.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToObjectArray() {
|
||||
Object[] objects = new Object[0];
|
||||
assertArrayEquals(objects, AbstractObjectUtils.toObjectArray(objects));
|
||||
assertNotNull(AbstractObjectUtils.toObjectArray(null));
|
||||
assertThrows(IllegalArgumentException.class, () -> AbstractObjectUtils.toObjectArray(new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullSafeEquals() {
|
||||
Integer o1 = new Integer(1111);
|
||||
Integer o2 = new Integer(1111);
|
||||
AbstractObjectUtils.nullSafeEquals(1, 1);
|
||||
assertTrue(AbstractObjectUtils.nullSafeEquals(o1, o2));
|
||||
assertTrue(AbstractObjectUtils.nullSafeEquals(null, null));
|
||||
|
||||
assertFalse(AbstractObjectUtils.nullSafeEquals(o1, null));
|
||||
assertFalse(AbstractObjectUtils.nullSafeEquals(null, o2));
|
||||
|
||||
assertTrue(AbstractObjectUtils.nullSafeEquals(1111, 1111));
|
||||
|
||||
assertTrue(AbstractObjectUtils.nullSafeEquals(new Integer[] {1, 2}, new Integer[] {1, 2}));
|
||||
assertFalse(AbstractObjectUtils.nullSafeEquals(new Integer[] {1, 2}, new Integer[] {1, 2, 3}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullSafeHashCode() {
|
||||
Object o = null;
|
||||
assertEquals(0, AbstractObjectUtils.nullSafeHashCode(o));
|
||||
assertNotEquals(0, AbstractObjectUtils.nullSafeHashCode(new Object[] {}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentityToString() {
|
||||
assertEquals("", AbstractObjectUtils.identityToString(null));
|
||||
|
||||
String str = "1";
|
||||
assertEquals(str.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(str)),
|
||||
AbstractObjectUtils.identityToString(str));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIdentityHexString() {
|
||||
assertEquals(Integer.toHexString(System.identityHashCode("1")), AbstractObjectUtils.getIdentityHexString("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDisplayString() {
|
||||
assertEquals("", AbstractObjectUtils.getDisplayString(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullSafeClassName() {
|
||||
assertEquals("null", AbstractObjectUtils.nullSafeClassName(null));
|
||||
assertEquals(Integer.class.getName(), AbstractObjectUtils.nullSafeClassName(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullSafeToString() {
|
||||
Object o = null;
|
||||
assertEquals("null", AbstractObjectUtils.nullSafeToString(o));
|
||||
assertSame("1", AbstractObjectUtils.nullSafeToString("1"));
|
||||
assertEquals("{1, 2}", AbstractObjectUtils.nullSafeToString(new Object[] {1, 2}));
|
||||
assertEquals("{true, false}", AbstractObjectUtils.nullSafeToString(new boolean[] {true, false}));
|
||||
assertEquals("{1}", AbstractObjectUtils.nullSafeToString(new byte[] {1}));
|
||||
assertEquals("{'a'}", AbstractObjectUtils.nullSafeToString(new char[] {'a'}));
|
||||
assertEquals("{1.1}", AbstractObjectUtils.nullSafeToString(new double[] {1.1d}));
|
||||
assertEquals("{1.1}", AbstractObjectUtils.nullSafeToString(new float[] {1.1f}));
|
||||
assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new int[] {11}));
|
||||
assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new long[] {11L}));
|
||||
assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new short[] {11}));
|
||||
}
|
||||
|
||||
}
|
@ -21,7 +21,8 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* ByteUtils Test.
|
||||
* ByteUtils Test.
|
||||
*
|
||||
* @ClassName: ByteUtilsTest
|
||||
* @Author: ChenHao26
|
||||
* @Date: 2022/8/22 10:58
|
||||
@ -48,6 +49,13 @@ public class ByteUtilsTest {
|
||||
Assert.assertEquals(str, "google");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForInputNull() {
|
||||
Assert.assertEquals(0, ByteUtils.toBytes(null).length);
|
||||
Assert.assertEquals(0, ByteUtils.toBytes((Object) null).length);
|
||||
Assert.assertEquals("", ByteUtils.toString(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEmpty() {
|
||||
byte[] bytes = ByteUtils.toBytes("");
|
||||
|
@ -20,7 +20,11 @@ import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClassUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testFindClassByName1() {
|
||||
Class<?> clazz = ClassUtils.findClassByName("java.lang.Integer");
|
||||
@ -50,4 +54,57 @@ public class ClassUtilsTest {
|
||||
public void testIsAssignableFrom() {
|
||||
Assert.assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForNameArray() throws ClassNotFoundException {
|
||||
Class clazz = ClassUtils.forName("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", null);
|
||||
Assert.assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName());
|
||||
clazz = ClassUtils.forName("java.lang.String[]", null);
|
||||
Assert.assertEquals("[Ljava.lang.String;", clazz.getName());
|
||||
clazz = ClassUtils.forName("[[Ljava.lang.String;", null);
|
||||
Assert.assertEquals("[[Ljava.lang.String;", clazz.getName());
|
||||
}
|
||||
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void testForNameNonExist() throws ClassNotFoundException {
|
||||
ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
|
||||
Field field = ClassUtils.class.getDeclaredField("PRIMITIVE_TYPE_NAME_MAP");
|
||||
field.setAccessible(true);
|
||||
Map<String, Class<?>> map = (Map<String, Class<?>>) field.get(null);
|
||||
map.put("Test", ClassUtilsTest.class);
|
||||
Assert.assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDefaultClassLoader() {
|
||||
ClassLoader cachedClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
try {
|
||||
Thread.currentThread().setContextClassLoader(null);
|
||||
Assert.assertNotNull(ClassUtils.getDefaultClassLoader());
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(cachedClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClassPackageAsResourcePath() throws ClassNotFoundException {
|
||||
Class noPackageClass = ClassUtils.forName("ClassUtilsTestMockClass", null);
|
||||
Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(null));
|
||||
Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass));
|
||||
Assert.assertEquals("com/alibaba/nacos/common/utils",
|
||||
ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertClassNameAndClassPath() {
|
||||
String name = ClassUtilsTest.class.getName();
|
||||
Assert.assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest",
|
||||
ClassUtils.convertClassNameToResourcePath(name));
|
||||
Assert.assertEquals(name,
|
||||
ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest"));
|
||||
}
|
||||
}
|
@ -22,14 +22,14 @@ import org.junit.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
import java.util.Vector;
|
||||
@ -38,7 +38,7 @@ import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Unit test of CollectionUtil.
|
||||
*
|
||||
*
|
||||
* @author <a href="mailto:jifeng.sun@outlook.com">sunjifeng</a>
|
||||
*/
|
||||
public class CollectionUtilsTest {
|
||||
@ -189,7 +189,7 @@ public class CollectionUtilsTest {
|
||||
Assert.assertEquals(0, CollectionUtils.size(Collections.emptyList()));
|
||||
Assert.assertEquals(1, CollectionUtils.size(Collections.singletonList("")));
|
||||
Assert.assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList())));
|
||||
|
||||
|
||||
// map
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
@ -197,8 +197,7 @@ public class CollectionUtilsTest {
|
||||
map.put("key2", "value2");
|
||||
Assert.assertEquals(2, CollectionUtils.size(map));
|
||||
map.put("key3", "value3");
|
||||
Assert.assertEquals(3,
|
||||
CollectionUtils.size(map));
|
||||
Assert.assertEquals(3, CollectionUtils.size(map));
|
||||
|
||||
// array
|
||||
Assert.assertEquals(1, CollectionUtils.size(new Object[] {"1"}));
|
||||
@ -318,7 +317,7 @@ public class CollectionUtilsTest {
|
||||
public boolean hasMoreElements() {
|
||||
return iterator.hasNext();
|
||||
}
|
||||
|
||||
|
||||
public T nextElement() {
|
||||
return iterator.next();
|
||||
}
|
||||
@ -341,10 +340,15 @@ public class CollectionUtilsTest {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetOnlyElementIllegalArgumentException() {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3);
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
CollectionUtils.getOnlyElement(list);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetOnlyElementIllegalArgumentException2() {
|
||||
CollectionUtils.getOnlyElement(null);
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void testGetOnlyElementNoSuchElementException() {
|
||||
List<Object> list = new ArrayList<>();
|
||||
@ -357,4 +361,35 @@ public class CollectionUtilsTest {
|
||||
int element = CollectionUtils.getOnlyElement(list);
|
||||
Assert.assertEquals(1, element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForNull() {
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(null, null));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForEquals() {
|
||||
List<String> list1 = Arrays.asList("1", "2", "3");
|
||||
List<String> list2 = Arrays.asList("1", "2", "3");
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list1, list1));
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list1, list2));
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list2, list1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForNotEquals() {
|
||||
List<String> list1 = Arrays.asList("1", "2", "3");
|
||||
List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||
List<String> list3 = Arrays.asList("1", "2", "3", "5");
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(list1, list2));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(list2, list3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsMapEmpty() {
|
||||
Assert.assertTrue(CollectionUtils.isMapEmpty(null));
|
||||
Assert.assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap()));
|
||||
}
|
||||
}
|
||||
|
@ -20,6 +20,7 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/**
|
||||
@ -44,4 +45,14 @@ public class DateFormatUtilsTest {
|
||||
buffer.append(hour);
|
||||
Assert.assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH"));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testForNullPointerExceptionWithDate() {
|
||||
DateFormatUtils.format(new Date(), null);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testForNullPointerExceptionWithPattern() {
|
||||
DateFormatUtils.format(null, "yyyyMdH");
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ExceptionUtilTest {
|
||||
|
||||
NacosRuntimeException nacosRuntimeException;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
RuntimeException caused = new RuntimeException("I'm caused exception.");
|
||||
nacosRuntimeException = new NacosRuntimeException(500, "Test", caused);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAllExceptionMsg() {
|
||||
String msg = ExceptionUtil.getAllExceptionMsg(nacosRuntimeException);
|
||||
assertEquals("caused: errCode: 500, errMsg: Test ;caused: I'm caused exception.;", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCause() {
|
||||
assertEquals("I'm caused exception.", ExceptionUtil.getCause(nacosRuntimeException).getMessage());
|
||||
NacosRuntimeException nreWithoutCaused = new NacosRuntimeException(500);
|
||||
assertEquals(nreWithoutCaused, ExceptionUtil.getCause(nreWithoutCaused));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStackTrace() {
|
||||
assertEquals("", ExceptionUtil.getStackTrace(null));
|
||||
String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException);
|
||||
assertTrue(stackTrace.contains(
|
||||
"com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test \n"));
|
||||
assertTrue(stackTrace.contains("at "));
|
||||
assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception.\n"));
|
||||
}
|
||||
}
|
@ -38,6 +38,7 @@ public class InetAddressValidatorTest {
|
||||
@Test
|
||||
public void isIPv6MixedAddress() {
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18"));
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18"));
|
||||
Assert.assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA"));
|
||||
}
|
||||
|
||||
@ -51,4 +52,10 @@ public class InetAddressValidatorTest {
|
||||
public void isIPv4Address() {
|
||||
Assert.assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isLinkLocalIPv6WithZoneIndex() {
|
||||
Assert.assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0"));
|
||||
Assert.assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd"));
|
||||
}
|
||||
}
|
||||
|
@ -24,6 +24,7 @@ import java.lang.reflect.Modifier;
|
||||
|
||||
/**
|
||||
* test IpUtil.
|
||||
*
|
||||
* @ClassName: IpUtilTest
|
||||
* @date 2020/9/3 10:31
|
||||
*/
|
||||
@ -56,7 +57,8 @@ public class InternetAddressUtilTest {
|
||||
|
||||
@Test
|
||||
public void testGetIPFromString() {
|
||||
Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("[::1]",
|
||||
InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
@ -66,7 +68,7 @@ public class InternetAddressUtilTest {
|
||||
"jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666"));
|
||||
|
||||
|
||||
Assert.assertEquals("",
|
||||
InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
@ -107,7 +109,7 @@ public class InternetAddressUtilTest {
|
||||
checkSplitIPPortStr("[2001:DB8:0:0:1::1]:88", false, "[2001:DB8:0:0:1::1]", "88");
|
||||
checkSplitIPPortStr("localhost:8848", false, "localhost", "8848");
|
||||
checkSplitIPPortStr("[dead::beef]:88", false, "[dead::beef]", "88");
|
||||
|
||||
|
||||
// illegal ip will get abnormal results
|
||||
checkSplitIPPortStr("::1:88", false, "", "", "1", "88");
|
||||
checkSplitIPPortStr("[::1:88", false, "[", "", "1", "88");
|
||||
@ -174,11 +176,22 @@ public class InternetAddressUtilTest {
|
||||
Assert.assertEquals("[::1]", InternetAddressUtil.localHostIP());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIpToInt() {
|
||||
Assert.assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1"));
|
||||
Assert.assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testIllegalIpToInt() {
|
||||
InternetAddressUtil.ipToInt("127.0.0.256");
|
||||
}
|
||||
|
||||
/**
|
||||
* checkSplitIpPortStr.
|
||||
* 2020/9/4 14:12
|
||||
* @param addr addr
|
||||
* @param isEx isEx
|
||||
* checkSplitIpPortStr. 2020/9/4 14:12
|
||||
*
|
||||
* @param addr addr
|
||||
* @param isEx isEx
|
||||
* @param equalsStrs equalsStrs
|
||||
*/
|
||||
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
|
||||
|
@ -19,11 +19,23 @@ package com.alibaba.nacos.common.utils;
|
||||
import org.apache.commons.io.Charsets;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import sun.security.action.GetPropertyAction;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.AccessController;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Unit test of IoUtils.
|
||||
@ -32,6 +44,142 @@ import java.io.InputStreamReader;
|
||||
*/
|
||||
public class IoUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testTryDecompressForNotGzip() throws Exception {
|
||||
byte[] testCase = "123".getBytes(Charsets.toCharset("UTF-8"));
|
||||
Assert.assertEquals(testCase, IoUtils.tryDecompress(testCase));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTryDecompressForGzip() throws Exception {
|
||||
byte[] testCase = IoUtils.tryCompress("123", "UTF-8");
|
||||
Assert.assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTryCompressWithEmptyString() {
|
||||
Assert.assertEquals(0, IoUtils.tryCompress("", "UTF-8").length);
|
||||
Assert.assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWriteStringToFile() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
file = File.createTempFile("test_writeStringToFile", ".txt");
|
||||
IoUtils.writeStringToFile(file, "123", "UTF-8");
|
||||
List<String> actual = IoUtils.readLines(new FileReader(file));
|
||||
Assert.assertEquals(1, actual.size());
|
||||
Assert.assertEquals("123", actual.get(0));
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.deleteOnExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToStringWithNull() throws IOException {
|
||||
Assert.assertEquals("", IoUtils.toString(null, "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToStringWithReader() throws IOException {
|
||||
String testCase = "123";
|
||||
Assert.assertEquals(testCase,
|
||||
IoUtils.toString(new ByteArrayInputStream(testCase.getBytes(Charsets.toCharset("UTF-8"))), "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForNullFile() throws IOException {
|
||||
IoUtils.delete(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSuccess() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
file = File.createTempFile("test_deleteForFile", ".txt");
|
||||
Assert.assertTrue(file.exists());
|
||||
IoUtils.delete(file);
|
||||
Assert.assertFalse(file.exists());
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.deleteOnExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testDeleteFileFailure() throws IOException {
|
||||
File file = mock(File.class);
|
||||
when(file.exists()).thenReturn(true);
|
||||
when(file.delete()).thenReturn(false);
|
||||
IoUtils.delete(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForDirectory() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
String tmpDir = AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir"));
|
||||
File tmpDirFile = new File(tmpDir, "IoUtilsTest");
|
||||
tmpDirFile.mkdirs();
|
||||
file = File.createTempFile("test_deleteForDirectory", ".txt", tmpDirFile);
|
||||
Assert.assertTrue(file.exists());
|
||||
IoUtils.delete(file.getParentFile());
|
||||
Assert.assertTrue(tmpDirFile.exists());
|
||||
Assert.assertFalse(file.exists());
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.getParentFile().deleteOnExit();
|
||||
file.deleteOnExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCleanDirectoryForNonExistingDirectory() throws IOException {
|
||||
File nonexistentDir = new File("non_exist");
|
||||
IoUtils.cleanDirectory(nonexistentDir);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCleanDirectoryForFile() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testCleanDirectoryWithEmptyDirectory() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testCleanDirectory() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
File mockSubFile = mock(File.class);
|
||||
when(mockSubFile.exists()).thenReturn(true);
|
||||
when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile});
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsGzipStreamWithNull() {
|
||||
Assert.assertFalse(IoUtils.isGzipStream(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsGzipStreamWithEmpty() {
|
||||
Assert.assertFalse(IoUtils.isGzipStream(new byte[0]));
|
||||
}
|
||||
|
||||
@Test()
|
||||
public void testCloseQuietly() throws IOException {
|
||||
BufferedReader br = new BufferedReader(
|
||||
@ -70,4 +218,13 @@ public class IoUtilsTest {
|
||||
Assert.fail();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseQuietlyForHttpConnection() throws IOException {
|
||||
HttpURLConnection conn = mock(HttpURLConnection.class);
|
||||
InputStream inputStream = mock(InputStream.class);
|
||||
when(conn.getInputStream()).thenReturn(inputStream);
|
||||
IoUtils.closeQuietly(conn);
|
||||
verify(inputStream).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -17,6 +17,7 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException;
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosSerializationException;
|
||||
import com.alibaba.nacos.common.model.RestResult;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
@ -52,14 +53,10 @@ public class JacksonUtilsTest {
|
||||
Assert.assertEquals("\"string\"", JacksonUtils.toJson("string"));
|
||||
Assert.assertEquals("30", JacksonUtils.toJson(new BigDecimal(30)));
|
||||
Assert.assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value")));
|
||||
Assert.assertEquals(
|
||||
"[{\"key\":\"value\"}]",
|
||||
JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value")))
|
||||
);
|
||||
Assert.assertEquals(
|
||||
"{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}",
|
||||
JacksonUtils.toJson(new TestOfAtomicObject())
|
||||
);
|
||||
Assert.assertEquals("[{\"key\":\"value\"}]",
|
||||
JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value"))));
|
||||
Assert.assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}",
|
||||
JacksonUtils.toJson(new TestOfAtomicObject()));
|
||||
Assert.assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate()));
|
||||
// only public
|
||||
Assert.assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier()));
|
||||
@ -67,10 +64,8 @@ public class JacksonUtilsTest {
|
||||
Assert.assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter()));
|
||||
// annotation available
|
||||
Assert.assertEquals(
|
||||
"{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}",
|
||||
JacksonUtils.toJson(new TestOfAnnotationSub())
|
||||
);
|
||||
"{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}", JacksonUtils.toJson(new TestOfAnnotationSub()));
|
||||
}
|
||||
|
||||
@Test(expected = NacosSerializationException.class)
|
||||
@ -84,35 +79,23 @@ public class JacksonUtilsTest {
|
||||
Assert.assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null));
|
||||
Assert.assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string"));
|
||||
Assert.assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30)));
|
||||
Assert.assertArrayEquals(
|
||||
"{\"key\":\"value\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value"))
|
||||
);
|
||||
Assert.assertArrayEquals(
|
||||
"[{\"key\":\"value\"}]".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value")))
|
||||
);
|
||||
Assert.assertArrayEquals(
|
||||
"{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAtomicObject())
|
||||
);
|
||||
Assert.assertArrayEquals("{\"key\":\"value\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value")));
|
||||
Assert.assertArrayEquals("[{\"key\":\"value\"}]".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value"))));
|
||||
Assert.assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAtomicObject()));
|
||||
Assert.assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate()));
|
||||
// only public
|
||||
Assert.assertArrayEquals(
|
||||
"{\"publicAccessModifier\":\"public\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAccessModifier())
|
||||
);
|
||||
Assert.assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAccessModifier()));
|
||||
// getter is also recognized
|
||||
Assert.assertArrayEquals(
|
||||
"{\"value\":\"value\",\"key\":\"key\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfGetter())
|
||||
);
|
||||
Assert.assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfGetter()));
|
||||
// annotation available
|
||||
Assert.assertArrayEquals(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}").getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAnnotationSub())
|
||||
);
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}").getBytes(), JacksonUtils.toJsonBytes(new TestOfAnnotationSub()));
|
||||
}
|
||||
|
||||
@Test(expected = NacosSerializationException.class)
|
||||
@ -129,36 +112,21 @@ public class JacksonUtilsTest {
|
||||
Assert.assertNull(JacksonUtils.toObj("null".getBytes(), Object.class));
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class));
|
||||
Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class));
|
||||
Assert.assertEquals(
|
||||
Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAtomicObject(),
|
||||
JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
TestOfAtomicObject.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfGetter(),
|
||||
JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAnnotationSub(),
|
||||
JacksonUtils.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class)
|
||||
);
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class));
|
||||
Assert.assertEquals(new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class));
|
||||
Assert.assertEquals(new TestOfGetter(),
|
||||
JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils
|
||||
.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -174,16 +142,12 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test
|
||||
public void testToObject3() {
|
||||
Assert.assertEquals(
|
||||
Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), TypeUtils.parameterize(Map.class,
|
||||
String.class, String.class))
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils.parameterize(List.class,
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)))
|
||||
);
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils
|
||||
.toObj("{\"key\":\"value\"}".getBytes(),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils
|
||||
.toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils
|
||||
.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -191,10 +155,8 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject4() {
|
||||
JacksonUtils.toObj(
|
||||
"{not_A}Json:String}".getBytes(),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)
|
||||
);
|
||||
JacksonUtils
|
||||
.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -211,47 +173,29 @@ public class JacksonUtilsTest {
|
||||
@Test
|
||||
public void testToObject6() {
|
||||
Assert.assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class));
|
||||
Assert.assertEquals(
|
||||
"string",
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new BigDecimal(30),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAtomicObject(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}"
|
||||
.getBytes()), TestOfAtomicObject.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfDate(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()),
|
||||
TestOfAccessModifier.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfGetter(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()),
|
||||
TestOfGetter.class)
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAnnotationSub(),
|
||||
JacksonUtils.toObj((new ByteArrayInputStream(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\","
|
||||
+ "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}")
|
||||
.getBytes())), TestOfAnnotation.class)
|
||||
);
|
||||
Assert.assertEquals("string",
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class));
|
||||
Assert.assertEquals(new BigDecimal(30),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class));
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()),
|
||||
TestOfAtomicObject.class));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class));
|
||||
Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()),
|
||||
TestOfAccessModifier.class));
|
||||
Assert.assertEquals(new TestOfGetter(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()),
|
||||
TestOfGetter.class));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\","
|
||||
+ "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes())),
|
||||
TestOfAnnotation.class));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -275,41 +219,36 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test
|
||||
public void testToObject9() {
|
||||
Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference<Object>() { }));
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference<String>() { }));
|
||||
Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference<BigDecimal>() { }));
|
||||
Assert.assertEquals(
|
||||
Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference<Map<String, String>>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference<List<Map<String, String>>>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAtomicObject(),
|
||||
JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
new TypeReference<TestOfAtomicObject>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference<TestOfDate>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(),
|
||||
new TypeReference<TestOfAccessModifier>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfGetter(),
|
||||
JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference<TestOfGetter>() { })
|
||||
);
|
||||
Assert.assertEquals(
|
||||
new TestOfAnnotationSub(),
|
||||
JacksonUtils.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(),
|
||||
new TypeReference<TestOfAnnotation>() { })
|
||||
);
|
||||
Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference<Object>() {
|
||||
}));
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference<String>() {
|
||||
}));
|
||||
Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference<BigDecimal>() {
|
||||
}));
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference<Map<String, String>>() {
|
||||
}));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference<List<Map<String, String>>>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
new TypeReference<TestOfAtomicObject>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference<TestOfDate>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils
|
||||
.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference<TestOfAccessModifier>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfGetter(), JacksonUtils
|
||||
.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference<TestOfGetter>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils
|
||||
.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(),
|
||||
new TypeReference<TestOfAnnotation>() {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -317,7 +256,8 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject10() {
|
||||
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() { });
|
||||
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -325,16 +265,12 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test
|
||||
public void testToObject11() {
|
||||
Assert.assertEquals(
|
||||
Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class))
|
||||
);
|
||||
Assert.assertEquals(
|
||||
Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils
|
||||
.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))
|
||||
);
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils
|
||||
.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -342,10 +278,8 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject12() {
|
||||
JacksonUtils.toObj(
|
||||
new ByteArrayInputStream("{not_A}Json:String}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)
|
||||
);
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -353,9 +287,8 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject13() {
|
||||
JacksonUtils.toObj(
|
||||
new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass()
|
||||
);
|
||||
JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -363,9 +296,7 @@ public class JacksonUtilsTest {
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject14() {
|
||||
JacksonUtils.toObj(
|
||||
(InputStream) null, Object.class.getGenericSuperclass()
|
||||
);
|
||||
JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -395,12 +326,10 @@ public class JacksonUtilsTest {
|
||||
@Test
|
||||
public void testRegisterSubtype() {
|
||||
JacksonUtils.registerSubtype(TestOfChild.class, "JacksonUtilsTest$TestOfChild");
|
||||
|
||||
Assert.assertEquals(
|
||||
new TestOfChild(),
|
||||
JacksonUtils.toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\","
|
||||
+ "\"childField\":\"childValue\"}", TestOfParent.class)
|
||||
);
|
||||
|
||||
Assert.assertEquals(new TestOfChild(), JacksonUtils
|
||||
.toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\","
|
||||
+ "\"childField\":\"childValue\"}", TestOfParent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -420,7 +349,7 @@ public class JacksonUtilsTest {
|
||||
public void testTransferToJsonNode() {
|
||||
JsonNode jsonNode1 = JacksonUtils.transferToJsonNode(Collections.singletonMap("key", "value"));
|
||||
Assert.assertEquals("value", jsonNode1.get("key").asText());
|
||||
|
||||
|
||||
JsonNode jsonNode2 = JacksonUtils.transferToJsonNode(new TestOfAtomicObject());
|
||||
Assert.assertEquals("0", jsonNode2.get("aLong").asText());
|
||||
Assert.assertEquals("1", jsonNode2.get("aInteger").asText());
|
||||
@ -432,7 +361,7 @@ public class JacksonUtilsTest {
|
||||
Assert.assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName());
|
||||
Assert.assertTrue(JacksonUtils.constructJavaType(String.class).isFinal());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testToJsonBytes() {
|
||||
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
||||
@ -440,7 +369,7 @@ public class JacksonUtilsTest {
|
||||
map.put("integer", 999);
|
||||
RestResult<Map<String, Object>> restResult = new RestResult();
|
||||
restResult.setData(map);
|
||||
|
||||
|
||||
byte[] bytes = JacksonUtils.toJsonBytes(restResult);
|
||||
String jsonFromBytes = ByteUtils.toString(bytes);
|
||||
Assert.assertTrue(jsonFromBytes.contains("\"code\":0"));
|
||||
@ -453,30 +382,48 @@ public class JacksonUtilsTest {
|
||||
// throw new NacosSerializationException(obj.getClass(), e);
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
// here is a verification to compare with the old implementation
|
||||
byte[] bytesFromOldImplementation = ByteUtils.toBytes(JacksonUtils.toJson(restResult));
|
||||
String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, Charset.forName(Constants.ENCODE));
|
||||
String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation,
|
||||
Charset.forName(Constants.ENCODE));
|
||||
Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0"));
|
||||
Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testToObjFromBytes() {
|
||||
String json = "{\"code\":0,\"data\":{\"string\":\"你好,中国!\",\"integer\":999}}";
|
||||
|
||||
|
||||
RestResult<Map<String, Object>> restResult = JacksonUtils.toObj(json, RestResult.class);
|
||||
Assert.assertEquals(0, restResult.getCode());
|
||||
Assert.assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
Assert.assertEquals(999, restResult.getData().get("integer"));
|
||||
|
||||
restResult = JacksonUtils.toObj(json, new TypeReference<RestResult<Map<String, Object>>>() { });
|
||||
|
||||
restResult = JacksonUtils.toObj(json, new TypeReference<RestResult<Map<String, Object>>>() {
|
||||
});
|
||||
Assert.assertEquals(0, restResult.getCode());
|
||||
Assert.assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
Assert.assertEquals(999, restResult.getData().get("integer"));
|
||||
}
|
||||
|
||||
@JsonPropertyOrder({ "aLong", "aInteger", "aBoolean"})
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForClassWithException() {
|
||||
JacksonUtils.toObj("aaa", JsonNode.class);
|
||||
}
|
||||
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForTypeWithException() {
|
||||
JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class));
|
||||
}
|
||||
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForTypeTypeReferenceWithException() {
|
||||
JacksonUtils.toObj("aaa", new TypeReference<JsonNode>() {
|
||||
});
|
||||
}
|
||||
|
||||
@JsonPropertyOrder({"aLong", "aInteger", "aBoolean"})
|
||||
static class TestOfAtomicObject {
|
||||
|
||||
public AtomicLong aLong = new AtomicLong(0);
|
||||
@ -561,7 +508,7 @@ public class JacksonUtilsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@JsonPropertyOrder({ "value", "key" })
|
||||
@JsonPropertyOrder({"value", "key"})
|
||||
static class TestOfGetter {
|
||||
|
||||
public String getKey() {
|
||||
@ -704,7 +651,7 @@ public class JacksonUtilsTest {
|
||||
static class TestOfParent {
|
||||
|
||||
public String parentField = "parentValue";
|
||||
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
@ -713,12 +660,12 @@ public class JacksonUtilsTest {
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
TestOfParent that = (TestOfParent) o;
|
||||
|
||||
|
||||
return parentField != null ? parentField.equals(that.parentField) : that.parentField == null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return parentField != null ? parentField.hashCode() : 0;
|
||||
@ -728,7 +675,7 @@ public class JacksonUtilsTest {
|
||||
static class TestOfChild extends TestOfParent {
|
||||
|
||||
public String childField = "childValue";
|
||||
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
@ -740,12 +687,12 @@ public class JacksonUtilsTest {
|
||||
if (!super.equals(o)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
TestOfChild that = (TestOfChild) o;
|
||||
|
||||
|
||||
return childField != null ? childField.equals(that.childField) : that.childField == null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = super.hashCode();
|
||||
|
@ -0,0 +1,65 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class LoggerUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testPrintIfDebugEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isDebugEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfDebugEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
Mockito.verify(logger, Mockito.times(1)).debug("test", "arg1", "arg2", "arg3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfInfoEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isInfoEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfInfoEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
Mockito.verify(logger, Mockito.times(1)).info("test", "arg1", "arg2", "arg3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfTraceEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isTraceEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfTraceEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
Mockito.verify(logger, Mockito.times(1)).trace("test", "arg1", "arg2", "arg3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfWarnEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isWarnEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfWarnEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
Mockito.verify(logger, Mockito.times(1)).warn("test", "arg1", "arg2", "arg3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfErrorEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isErrorEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfErrorEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
Mockito.verify(logger, Mockito.times(1)).error("test", "arg1", "arg2", "arg3");
|
||||
}
|
||||
|
||||
}
|
@ -16,51 +16,135 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Dictionary;
|
||||
import java.util.HashMap;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MapUtilTest {
|
||||
|
||||
@Test
|
||||
public void testMap() {
|
||||
Map<Object, Object> map = new HashMap<Object, Object>();
|
||||
|
||||
public void testIsEmptyAndNotEmptyMap() {
|
||||
Map<Object, Object> map = null;
|
||||
assertTrue(MapUtil.isEmpty(map));
|
||||
assertFalse(MapUtil.isNotEmpty(map));
|
||||
map = new HashMap<>();
|
||||
assertTrue(MapUtil.isEmpty(map));
|
||||
assertFalse(MapUtil.isNotEmpty(map));
|
||||
map.put("a", "b");
|
||||
assertFalse(MapUtil.isEmpty(map));
|
||||
assertTrue(MapUtil.isNotEmpty(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmptyOrEmptyDictionary() {
|
||||
Dictionary<Object, Object> dictionary = null;
|
||||
assertTrue(MapUtil.isEmpty(dictionary));
|
||||
assertFalse(MapUtil.isNotEmpty(dictionary));
|
||||
dictionary = new Hashtable<>();
|
||||
assertTrue(MapUtil.isEmpty(dictionary));
|
||||
assertFalse(MapUtil.isNotEmpty(dictionary));
|
||||
dictionary.put("a", "b");
|
||||
assertFalse(MapUtil.isEmpty(dictionary));
|
||||
assertTrue(MapUtil.isNotEmpty(dictionary));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutIfValNoNull() {
|
||||
Map<Object, Object> map = new HashMap<>();
|
||||
MapUtil.putIfValNoNull(map, "key-1", null);
|
||||
Assert.assertFalse(map.containsKey("key-1"));
|
||||
assertTrue(map.isEmpty());
|
||||
MapUtil.putIfValNoNull(map, "key-1", "null");
|
||||
assertTrue(map.containsKey("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutIfValNoEmptyMap() {
|
||||
Map<Object, Object> map = new HashMap<>();
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-str", null);
|
||||
Assert.assertFalse(map.containsKey("key-str"));
|
||||
assertFalse(map.containsKey("key-str"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-str", "");
|
||||
Assert.assertFalse(map.containsKey("key-str"));
|
||||
assertFalse(map.containsKey("key-str"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-str", "1");
|
||||
Assert.assertTrue(map.containsKey("key-str"));
|
||||
assertTrue(map.containsKey("key-str"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-list", null);
|
||||
Assert.assertFalse(map.containsKey("key-list"));
|
||||
assertFalse(map.containsKey("key-list"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-list", Collections.emptyList());
|
||||
Assert.assertFalse(map.containsKey("key-list"));
|
||||
assertFalse(map.containsKey("key-list"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-list", Collections.singletonList(1));
|
||||
Assert.assertTrue(map.containsKey("key-list"));
|
||||
assertTrue(map.containsKey("key-list"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-map", null);
|
||||
Assert.assertFalse(map.containsKey("key-map"));
|
||||
assertFalse(map.containsKey("key-map"));
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-map", Collections.emptyMap());
|
||||
Assert.assertFalse(map.containsKey("key-map"));
|
||||
assertFalse(map.containsKey("key-map"));
|
||||
|
||||
Map<String, String> map1 = new HashMap<String, String>();
|
||||
Map<String, String> map1 = new HashMap<>();
|
||||
map1.put("1123", "123");
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-map", map1);
|
||||
Assert.assertTrue(map.containsKey("key-map"));
|
||||
assertTrue(map.containsKey("key-map"));
|
||||
|
||||
Dictionary dictionary = Mockito.mock(Dictionary.class);
|
||||
when(dictionary.isEmpty()).thenReturn(true);
|
||||
MapUtil.putIfValNoEmpty(map, "key-dict", dictionary);
|
||||
assertFalse(map.containsKey("key-dict"));
|
||||
when(dictionary.isEmpty()).thenReturn(false);
|
||||
MapUtil.putIfValNoEmpty(map, "key-dict", dictionary);
|
||||
assertTrue(map.containsKey("key-dict"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComputeIfAbsent() {
|
||||
Map<String, String> target = new HashMap<>();
|
||||
String key = "key";
|
||||
String param1 = "param1";
|
||||
String param2 = "param2";
|
||||
BiFunction<String, String, String> mappingFunction = (p1, p2) -> p1 + p2;
|
||||
|
||||
String result = MapUtil.computeIfAbsent(target, key, mappingFunction, param1, param2);
|
||||
assertEquals("param1param2", result);
|
||||
|
||||
// Test that the mappingFunction is only called once
|
||||
AtomicInteger counter = new AtomicInteger();
|
||||
mappingFunction = (p1, p2) -> {
|
||||
counter.incrementAndGet();
|
||||
return p1 + p2;
|
||||
};
|
||||
|
||||
result = MapUtil.computeIfAbsent(target, key, mappingFunction, param1, param2);
|
||||
assertEquals("param1param2", result);
|
||||
assertEquals(0, counter.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveKey() {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
map.put("A", 1);
|
||||
map.put("B", 2);
|
||||
map.put("C", 3);
|
||||
|
||||
MapUtil.removeKey(map, "B", integer -> integer == 1);
|
||||
assertEquals(3, map.size());
|
||||
MapUtil.removeKey(map, "B", integer -> integer == 2);
|
||||
assertEquals(2, map.size());
|
||||
}
|
||||
}
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
@ -27,6 +28,11 @@ import org.junit.Test;
|
||||
*/
|
||||
public class NamespaceUtilTest {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
NamespaceUtil.setNamespaceDefaultId("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessTenantParameter() {
|
||||
String strPublic = "public";
|
||||
@ -44,4 +50,9 @@ public class NamespaceUtilTest {
|
||||
Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetNamespaceDefaultId() {
|
||||
NamespaceUtil.setNamespaceDefaultId("Deprecated");
|
||||
Assert.assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId());
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ObservableTest {
|
||||
|
||||
@Mock
|
||||
private Observer observer;
|
||||
|
||||
private Observable observable;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
observable = new Observable();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddObserver() {
|
||||
observable.addObserver(observer);
|
||||
assertEquals(1, observable.countObservers());
|
||||
verify(observer).update(observable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteObserver() {
|
||||
observable.addObserver(observer);
|
||||
assertEquals(1, observable.countObservers());
|
||||
observable.deleteObserver(observer);
|
||||
assertEquals(0, observable.countObservers());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyObservers() {
|
||||
observable.addObserver(observer);
|
||||
reset(observer);
|
||||
observable.notifyObservers();
|
||||
assertFalse(observable.hasChanged());
|
||||
verify(observer, never()).update(observable);
|
||||
observable.setChanged();
|
||||
assertTrue(observable.hasChanged());
|
||||
observable.notifyObservers();
|
||||
verify(observer).update(observable);
|
||||
assertFalse(observable.hasChanged());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteObservers() {
|
||||
observable.addObserver(observer);
|
||||
observable.deleteObservers();
|
||||
assertEquals(1, observable.countObservers());
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PairTest {
|
||||
|
||||
@Test
|
||||
public void testPair() {
|
||||
Pair<String, String> pair = Pair.with("a", "b");
|
||||
assertEquals("a", pair.getFirst());
|
||||
assertEquals("b", pair.getSecond());
|
||||
}
|
||||
}
|
@ -21,19 +21,42 @@ import org.junit.Test;
|
||||
|
||||
/**
|
||||
* test RandomUtils.
|
||||
*
|
||||
* @author zzq
|
||||
*/
|
||||
public class RandomUtilsTest {
|
||||
|
||||
@Test
|
||||
public void nextLong() {
|
||||
public void testNextLong() {
|
||||
final long result = RandomUtils.nextLong(1L, 199L);
|
||||
Assert.assertTrue(result >= 1L && result < 199L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nextInt() {
|
||||
public void testNextLongWithSame() {
|
||||
final long result = RandomUtils.nextLong(1L, 1L);
|
||||
Assert.assertEquals(1L, result);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testNextLongWithIllegalArgumentException() {
|
||||
RandomUtils.nextLong(999L, 199L);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testNextLongWithIllegalArgumentException2() {
|
||||
RandomUtils.nextLong(-10L, 199L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextInt() {
|
||||
final int result = RandomUtils.nextInt(1, 199);
|
||||
Assert.assertTrue(result >= 1 && result < 199);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextIntWithSame() {
|
||||
final int result = RandomUtils.nextInt(1, 1);
|
||||
Assert.assertEquals(1, result);
|
||||
}
|
||||
}
|
||||
|
@ -20,7 +20,11 @@ import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ -31,38 +35,101 @@ import java.util.List;
|
||||
* @date 2022/08/19
|
||||
*/
|
||||
public class ReflectUtilsTest {
|
||||
|
||||
|
||||
List<String> listStr;
|
||||
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
listStr = new ArrayList<>(2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void getFieldValue() {
|
||||
public void testGetFieldValue() {
|
||||
Object elementData = ReflectUtils.getFieldValue(listStr, "elementData");
|
||||
Assert.assertTrue(elementData instanceof Object[]);
|
||||
Assert.assertEquals(((Object[]) elementData).length, 2);
|
||||
Assert.assertEquals(2, ((Object[]) elementData).length);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void testGetFieldValueWithoutField() {
|
||||
ReflectUtils.getFieldValue(listStr, "elementDataxx");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getFieldValue2() {
|
||||
public void testGetFieldValueWithDefault() {
|
||||
Object elementData = ReflectUtils.getFieldValue(listStr, "elementDataxx", 3);
|
||||
Assert.assertEquals(elementData, 3);
|
||||
elementData = ReflectUtils.getFieldValue(listStr, "elementData", 3);
|
||||
Assert.assertTrue(elementData instanceof Object[]);
|
||||
Assert.assertEquals(2, ((Object[]) elementData).length);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void getField() {
|
||||
try {
|
||||
Field field = listStr.getClass().getDeclaredField("elementData");
|
||||
field.setAccessible(true);
|
||||
Object elementData = ReflectUtils.getField(field, listStr);
|
||||
Assert.assertTrue(elementData instanceof Object[]);
|
||||
} catch (NoSuchFieldException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
public void testGetField() throws NoSuchFieldException {
|
||||
Field field = listStr.getClass().getDeclaredField("elementData");
|
||||
field.setAccessible(true);
|
||||
Object elementData = ReflectUtils.getField(field, listStr);
|
||||
Assert.assertTrue(elementData instanceof Object[]);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testGetFieldWithoutAccess() throws NoSuchFieldException {
|
||||
Field field = listStr.getClass().getDeclaredField("elementData");
|
||||
ReflectUtils.getField(field, listStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvokeMethod() throws Exception {
|
||||
Method method = listStr.getClass().getDeclaredMethod("grow", int.class);
|
||||
method.setAccessible(true);
|
||||
ReflectUtils.invokeMethod(method, listStr, 4);
|
||||
Object elementData = ReflectUtils.getFieldValue(listStr, "elementData");
|
||||
Assert.assertEquals(4, ((Object[]) elementData).length);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testInvokeMethodWithoutAccess() throws Exception {
|
||||
Method method = listStr.getClass().getDeclaredMethod("grow", int.class);
|
||||
ReflectUtils.invokeMethod(method, listStr, 4);
|
||||
}
|
||||
|
||||
@Test(expected = UndeclaredThrowableException.class)
|
||||
public void testHandleReflectionException() {
|
||||
try {
|
||||
NoSuchMethodException exception = new NoSuchMethodException("test");
|
||||
ReflectUtils.handleReflectionException(exception);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("Method not found: test", e.getMessage());
|
||||
}
|
||||
try {
|
||||
IllegalAccessException exception = new IllegalAccessException("test");
|
||||
ReflectUtils.handleReflectionException(exception);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("Could not access method or field: test", e.getMessage());
|
||||
}
|
||||
RuntimeException exception = new RuntimeException("test");
|
||||
try {
|
||||
ReflectUtils.handleReflectionException(exception);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals(exception, e);
|
||||
}
|
||||
try {
|
||||
InvocationTargetException invocationTargetException = new InvocationTargetException(exception);
|
||||
ReflectUtils.handleReflectionException(invocationTargetException);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals(exception, e);
|
||||
}
|
||||
ReflectUtils.handleReflectionException(new IOException());
|
||||
}
|
||||
|
||||
@Test(expected = UndeclaredThrowableException.class)
|
||||
public void testRethrowRuntimeException() {
|
||||
ClassFormatError error = new ClassFormatError("test");
|
||||
try {
|
||||
ReflectUtils.rethrowRuntimeException(error);
|
||||
} catch (Error e) {
|
||||
Assert.assertEquals(error, e);
|
||||
}
|
||||
ReflectUtils.rethrowRuntimeException(new IOException());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,147 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ResourceUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testGetResourceUrlForClasspath() throws IOException {
|
||||
URL url = ResourceUtils.getResourceUrl("classpath:test-tls-cert.pem");
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test(expected = FileNotFoundException.class)
|
||||
public void testGetResourceUrlForClasspathNotExists() throws IOException {
|
||||
ResourceUtils.getResourceUrl("classpath:non-exist.pem");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceUrlForFile() throws IOException {
|
||||
File file = File.createTempFile("test", ".txt");
|
||||
try {
|
||||
URL url = ResourceUtils.getResourceUrl("file://" + file.getPath());
|
||||
assertNotNull(url);
|
||||
} finally {
|
||||
file.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceUrlForFileWithoutProtocol() throws IOException {
|
||||
File file = File.createTempFile("test", ".txt");
|
||||
try {
|
||||
URL url = ResourceUtils.getResourceUrl(file.getPath());
|
||||
assertNotNull(url);
|
||||
} finally {
|
||||
file.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceUrlFromLoader() throws IOException {
|
||||
URL url = ResourceUtils.getResourceUrl(this.getClass().getClassLoader(), "test-tls-cert.pem");
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceUrlFromSystemLoader() throws IOException {
|
||||
URL url = ResourceUtils.getResourceUrl(null, "test-tls-cert.pem");
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testGetResourceUrlFromLoaderWithoutExist() throws IOException {
|
||||
URL url = ResourceUtils.getResourceUrl(null, "non-exist");
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsStreamForClasspath() throws IOException {
|
||||
try (InputStream inputStream = ResourceUtils.getResourceAsStream("test-tls-cert.pem")) {
|
||||
assertNotNull(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsStreamForClasspathFromSystem() throws IOException {
|
||||
try (InputStream inputStream = ResourceUtils.getResourceAsStream(null, "test-tls-cert.pem")) {
|
||||
assertNotNull(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testGetResourceAsStreamForClasspathWithoutExist() throws IOException {
|
||||
URL url = ResourceUtils.getResourceUrl("non-exist");
|
||||
ResourceUtils.getResourceAsStream(null, url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsPropertiesForClasspath() throws IOException {
|
||||
Properties properties = ResourceUtils.getResourceAsProperties("resource_utils_test.properties");
|
||||
assertNotNull(properties);
|
||||
assertTrue(properties.containsKey("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsReader() throws IOException {
|
||||
try (Reader reader = ResourceUtils.getResourceAsReader("resource_utils_test.properties", "UTF-8")) {
|
||||
assertNotNull(reader);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsReaderWithLoader() throws IOException {
|
||||
try (Reader reader = ResourceUtils
|
||||
.getResourceAsReader(ResourceUtilsTest.class.getClassLoader(), "resource_utils_test.properties",
|
||||
"UTF-8")) {
|
||||
assertNotNull(reader);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsFile() throws IOException {
|
||||
File file = ResourceUtils.getResourceAsFile("classpath:resource_utils_test.properties");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsFileByUrl() throws IOException {
|
||||
File file = ResourceUtils
|
||||
.getResourceAsFile(ResourceUtils.getResourceUrl("classpath:resource_utils_test.properties"));
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetResourceAsFileByLoader() throws IOException {
|
||||
File file = ResourceUtils
|
||||
.getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties");
|
||||
assertNotNull(file);
|
||||
}
|
||||
}
|
@ -24,6 +24,7 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* String utils.
|
||||
*
|
||||
* @author zzq
|
||||
*/
|
||||
public class StringUtilsTest {
|
||||
@ -77,7 +78,24 @@ public class StringUtilsTest {
|
||||
Assert.assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL"));
|
||||
Assert.assertEquals(" ", StringUtils.defaultIfEmpty(" ", "NULL"));
|
||||
Assert.assertEquals("bat", StringUtils.defaultIfEmpty("bat", "NULL"));
|
||||
Assert.assertEquals(null, StringUtils.defaultIfEmpty("", null));
|
||||
Assert.assertNull(StringUtils.defaultIfEmpty("", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultIfBlank() {
|
||||
Assert.assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL"));
|
||||
Assert.assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL"));
|
||||
Assert.assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL"));
|
||||
Assert.assertEquals("bat", StringUtils.defaultIfBlank("bat", "NULL"));
|
||||
Assert.assertNull(StringUtils.defaultIfBlank("", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultEmptyIfBlank() {
|
||||
Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(null));
|
||||
Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(""));
|
||||
Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(" "));
|
||||
Assert.assertEquals("bat", StringUtils.defaultEmptyIfBlank("bat"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -125,11 +143,6 @@ public class StringUtilsTest {
|
||||
Assert.assertEquals("abc", StringUtils.join(Arrays.asList("a", "b", "c"), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void escapeJavaScript() {
|
||||
//TODO
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContainsIgnoreCase() {
|
||||
Assert.assertFalse(StringUtils.containsIgnoreCase(null, "1"));
|
||||
@ -185,6 +198,7 @@ public class StringUtilsTest {
|
||||
Assert.assertFalse(StringUtils.startsWith("abcdef", null));
|
||||
Assert.assertTrue(StringUtils.startsWith("abcdef", "abc"));
|
||||
Assert.assertFalse(StringUtils.startsWith("ABCDEF", "abc"));
|
||||
Assert.assertFalse(StringUtils.startsWith("ABC", "ABCDEF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -217,8 +231,283 @@ public class StringUtilsTest {
|
||||
public void testSplit() {
|
||||
Assert.assertNull(StringUtils.split(null, ","));
|
||||
Assert.assertArrayEquals(new String[0], StringUtils.split("", ","));
|
||||
Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null));
|
||||
Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null));
|
||||
Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":"));
|
||||
Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null));
|
||||
Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null));
|
||||
Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTokenizeToStringArray() {
|
||||
// Test case 1: Empty string
|
||||
String str1 = "";
|
||||
String delimiters1 = ",";
|
||||
boolean trimTokens1 = true;
|
||||
boolean ignoreEmptyTokens1 = false;
|
||||
String[] expected1 = new String[0];
|
||||
String[] result1 = StringUtils.tokenizeToStringArray(str1, delimiters1, trimTokens1, ignoreEmptyTokens1);
|
||||
Assert.assertArrayEquals(expected1, result1);
|
||||
|
||||
// Test case 2: Null string
|
||||
String str2 = null;
|
||||
String delimiters2 = " ";
|
||||
boolean trimTokens2 = false;
|
||||
boolean ignoreEmptyTokens2 = true;
|
||||
String[] expected2 = new String[0];
|
||||
String[] result2 = StringUtils.tokenizeToStringArray(str2, delimiters2, trimTokens2, ignoreEmptyTokens2);
|
||||
Assert.assertArrayEquals(expected2, result2);
|
||||
|
||||
// Test case 3: Single token
|
||||
String str3 = "Hello";
|
||||
String delimiters3 = ",";
|
||||
boolean trimTokens3 = true;
|
||||
boolean ignoreEmptyTokens3 = false;
|
||||
String[] expected3 = {"Hello"};
|
||||
String[] result3 = StringUtils.tokenizeToStringArray(str3, delimiters3, trimTokens3, ignoreEmptyTokens3);
|
||||
Assert.assertArrayEquals(expected3, result3);
|
||||
|
||||
// Test case 4: Multiple tokens with trimming
|
||||
String str4 = " Hello, World, ";
|
||||
String delimiters4 = ",";
|
||||
boolean trimTokens4 = true;
|
||||
boolean ignoreEmptyTokens4 = false;
|
||||
String[] expected4 = {"Hello", "World", ""};
|
||||
String[] result4 = StringUtils.tokenizeToStringArray(str4, delimiters4, trimTokens4, ignoreEmptyTokens4);
|
||||
Assert.assertArrayEquals(expected4, result4);
|
||||
|
||||
// Test case 5: Multiple tokens with empty tokens ignored
|
||||
String str5 = " ,Hello, ,World, ";
|
||||
String delimiters5 = ",";
|
||||
boolean trimTokens5 = true;
|
||||
boolean ignoreEmptyTokens5 = true;
|
||||
String[] expected5 = {"Hello", "World"};
|
||||
String[] result5 = StringUtils.tokenizeToStringArray(str5, delimiters5, trimTokens5, ignoreEmptyTokens5);
|
||||
Assert.assertArrayEquals(expected5, result5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasText() {
|
||||
// Test case 1: Empty string
|
||||
Assert.assertFalse(StringUtils.hasText(""));
|
||||
|
||||
// Test case 2: String with whitespace only
|
||||
Assert.assertFalse(StringUtils.hasText(" "));
|
||||
|
||||
// Test case 3: Null string
|
||||
Assert.assertFalse(StringUtils.hasText(null));
|
||||
|
||||
// Test case 4: String with non-whitespace characters
|
||||
Assert.assertTrue(StringUtils.hasText("hello"));
|
||||
|
||||
// Test case 5: String with both text and whitespace
|
||||
Assert.assertTrue(StringUtils.hasText(" hello "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCleanPath() {
|
||||
// Test case 1: path with no length
|
||||
String path1 = "";
|
||||
String expected1 = "";
|
||||
Assert.assertEquals(expected1, StringUtils.cleanPath(path1));
|
||||
|
||||
// Test case 2: normal path
|
||||
String path2 = "path/to/file";
|
||||
String expected2 = "path/to/file";
|
||||
Assert.assertEquals(expected2, StringUtils.cleanPath(path2));
|
||||
|
||||
// Test case 3: path with Windows folder separator
|
||||
String path3 = "path\\to\\文件";
|
||||
String expected3 = "path/to/文件";
|
||||
Assert.assertEquals(expected3, StringUtils.cleanPath(path3));
|
||||
|
||||
// Test case 4: path with dot
|
||||
String path4 = "path/..";
|
||||
String expected4 = "";
|
||||
Assert.assertEquals(expected4, StringUtils.cleanPath(path4));
|
||||
|
||||
// Test case 5: path with top path
|
||||
String path5 = "path/../top";
|
||||
String expected5 = "top";
|
||||
Assert.assertEquals(expected5, StringUtils.cleanPath(path5));
|
||||
|
||||
// Test case 6: path with multiple top path
|
||||
String path6 = "path/../../top";
|
||||
String expected6 = "../top";
|
||||
Assert.assertEquals(expected6, StringUtils.cleanPath(path6));
|
||||
|
||||
// Test case 7: path with leading colon
|
||||
String path7 = "file:../top";
|
||||
String expected7 = "file:../top";
|
||||
Assert.assertEquals(expected7, StringUtils.cleanPath(path7));
|
||||
|
||||
// Test case 8: path with leading slash
|
||||
String path8 = "file:/path/../file";
|
||||
String expected8 = "file:/file";
|
||||
Assert.assertEquals(expected8, StringUtils.cleanPath(path8));
|
||||
|
||||
// Test case 9: path with empty prefix
|
||||
String path9 = "file:path/../file";
|
||||
String expected9 = "file:file";
|
||||
Assert.assertEquals(expected9, StringUtils.cleanPath(path9));
|
||||
|
||||
// Test case 10: prefix contain separator
|
||||
String path10 = "file/:path/../file";
|
||||
String expected10 = "file/file";
|
||||
Assert.assertEquals(expected10, StringUtils.cleanPath(path10));
|
||||
|
||||
// Test case 11: dot in file name
|
||||
String path11 = "file:/path/to/file.txt";
|
||||
String expected11 = "file:/path/to/file.txt";
|
||||
Assert.assertEquals(expected11, StringUtils.cleanPath(path11));
|
||||
|
||||
// Test case 12: dot in path
|
||||
String path12 = "file:/path/./file.txt";
|
||||
String expected12 = "file:/path/file.txt";
|
||||
Assert.assertEquals(expected12, StringUtils.cleanPath(path12));
|
||||
|
||||
// Test case 13: path with dot and slash
|
||||
String path13 = "file:aaa/../";
|
||||
String expected13 = "file:./";
|
||||
Assert.assertEquals(expected13, StringUtils.cleanPath(path13));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelimitedListToStringArrayWithNull() {
|
||||
Assert.assertEquals(0, StringUtils.delimitedListToStringArray(null, ",", "").length);
|
||||
Assert.assertEquals(1, StringUtils.delimitedListToStringArray("a,b", null, "").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelimitedListToStringArrayWithEmptyDelimiter() {
|
||||
String testCase = "a,b";
|
||||
String[] actual = StringUtils.delimitedListToStringArray(testCase, "", "");
|
||||
Assert.assertEquals(3, actual.length);
|
||||
Assert.assertEquals("a", actual[0]);
|
||||
Assert.assertEquals(",", actual[1]);
|
||||
Assert.assertEquals("b", actual[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteAny() {
|
||||
// Test case 1: inString is empty, charsToDelete is empty
|
||||
String inString1 = "";
|
||||
String charsToDelete1 = "";
|
||||
Assert.assertEquals("", StringUtils.deleteAny(inString1, charsToDelete1));
|
||||
|
||||
// Test case 2: inString is empty, charsToDelete is not empty
|
||||
String inString2 = "";
|
||||
String charsToDelete2 = "abc";
|
||||
Assert.assertEquals("", StringUtils.deleteAny(inString2, charsToDelete2));
|
||||
|
||||
// Test case 3: inString is not empty, charsToDelete is empty
|
||||
String inString3 = "abc";
|
||||
String charsToDelete3 = "";
|
||||
Assert.assertEquals("abc", StringUtils.deleteAny(inString3, charsToDelete3));
|
||||
|
||||
// Test case 4: inString is not empty, charsToDelete is not empty
|
||||
String inString4 = "abc";
|
||||
String charsToDelete4 = "a";
|
||||
Assert.assertEquals("bc", StringUtils.deleteAny(inString4, charsToDelete4));
|
||||
|
||||
// Test case 5: inString contains special characters
|
||||
String inString5 = "abc\n";
|
||||
String charsToDelete5 = "\n";
|
||||
Assert.assertEquals("abc", StringUtils.deleteAny(inString5, charsToDelete5));
|
||||
|
||||
// Test case 6: inString not contains special characters
|
||||
String inString6 = "abc\n";
|
||||
String charsToDelete6 = "d";
|
||||
Assert.assertEquals("abc\n", StringUtils.deleteAny(inString6, charsToDelete6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplace() {
|
||||
// Test case 1: pattern is empty
|
||||
Assert.assertEquals("abc", StringUtils.replace("abc", "", "a"));
|
||||
|
||||
// Test case 2: oldPattern less than newPattern
|
||||
Assert.assertEquals("aabc", StringUtils.replace("abc", "a", "aa"));
|
||||
|
||||
// Test case 3: oldPattern more than newPattern
|
||||
Assert.assertEquals("dc", StringUtils.replace("abc", "ab", "d"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApplyRelativePath() {
|
||||
// Test case 1
|
||||
String path1 = "/path/to/file";
|
||||
String relativePath1 = "subfolder/subfile";
|
||||
String expected1 = "/path/to/subfolder/subfile";
|
||||
String result1 = StringUtils.applyRelativePath(path1, relativePath1);
|
||||
Assert.assertEquals(expected1, result1);
|
||||
|
||||
// Test case 2
|
||||
String path2 = "path/to/file";
|
||||
String relativePath2 = "subfolder/subfile";
|
||||
String expected2 = "path/to/subfolder/subfile";
|
||||
String result2 = StringUtils.applyRelativePath(path2, relativePath2);
|
||||
Assert.assertEquals(expected2, result2);
|
||||
|
||||
// Test case 3
|
||||
String path3 = "/path/to/file";
|
||||
String relativePath3 = "/subfolder/subfile";
|
||||
String expected3 = "/path/to/subfolder/subfile";
|
||||
String result3 = StringUtils.applyRelativePath(path3, relativePath3);
|
||||
Assert.assertEquals(expected3, result3);
|
||||
|
||||
//Test case 4
|
||||
String path4 = "file";
|
||||
String relativePath4 = "/subfolder/subfile";
|
||||
String expected4 = "/subfolder/subfile";
|
||||
String result4 = StringUtils.applyRelativePath(path4, relativePath4);
|
||||
Assert.assertEquals(expected4, result4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFilename() {
|
||||
// Test case 1: null path
|
||||
String path1 = null;
|
||||
String result1 = StringUtils.getFilename(path1);
|
||||
Assert.assertNull(result1);
|
||||
|
||||
// Test case 2: path without separator
|
||||
String path2 = "myFile.txt";
|
||||
String expectedResult2 = "myFile.txt";
|
||||
String result2 = StringUtils.getFilename(path2);
|
||||
Assert.assertEquals(expectedResult2, result2);
|
||||
|
||||
// Test case 3: path with separator
|
||||
String path3 = "myPath/myFile.txt";
|
||||
String expectedResult3 = "myFile.txt";
|
||||
String result3 = StringUtils.getFilename(path3);
|
||||
Assert.assertEquals(expectedResult3, result3);
|
||||
|
||||
// Test case 4: path with multiple separators
|
||||
String path4 = "myPath/subPath/myFile.txt";
|
||||
String expectedResult4 = "myFile.txt";
|
||||
String result4 = StringUtils.getFilename(path4);
|
||||
Assert.assertEquals(expectedResult4, result4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCapitalize() {
|
||||
// Test for an empty string
|
||||
String str1 = "";
|
||||
Assert.assertEquals("", StringUtils.capitalize(str1));
|
||||
|
||||
// Test for a single word string
|
||||
String str2 = "hello";
|
||||
Assert.assertEquals("Hello", StringUtils.capitalize(str2));
|
||||
|
||||
// Test for a multiple word string
|
||||
String str3 = "hello world";
|
||||
Assert.assertEquals("Hello world", StringUtils.capitalize(str3));
|
||||
|
||||
// Test for a string with special characters
|
||||
String str4 = "!@#$%^&*()";
|
||||
Assert.assertEquals("!@#$%^&*()", StringUtils.capitalize(str4));
|
||||
|
||||
// Test for a string with numbers
|
||||
String str5 = "abc123";
|
||||
Assert.assertEquals("Abc123", StringUtils.capitalize(str5));
|
||||
}
|
||||
}
|
||||
|
@ -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.utils;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ThreadUtilsTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
System.setProperty("nacos.common.processors", "2");
|
||||
executorService = Executors.newFixedThreadPool(1);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
System.setProperty("nacos.common.processors", "");
|
||||
ThreadUtils.shutdownThreadPool(executorService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLatchAwait() {
|
||||
final CountDownLatch countDownLatch = new CountDownLatch(1);
|
||||
long currentTime = System.currentTimeMillis();
|
||||
executorService.execute(() -> {
|
||||
ThreadUtils.sleep(100);
|
||||
ThreadUtils.countDown(countDownLatch);
|
||||
});
|
||||
ThreadUtils.latchAwait(countDownLatch);
|
||||
assertTrue(System.currentTimeMillis() - currentTime >= 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLatchAwaitForTimeout() {
|
||||
final CountDownLatch countDownLatch = new CountDownLatch(1);
|
||||
long currentTime = System.currentTimeMillis();
|
||||
ThreadUtils.latchAwait(countDownLatch, 50, TimeUnit.MILLISECONDS);
|
||||
assertTrue(System.currentTimeMillis() - currentTime >= 50);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetSuitableThreadCount() {
|
||||
assertEquals(4, ThreadUtils.getSuitableThreadCount());
|
||||
assertEquals(8, ThreadUtils.getSuitableThreadCount(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testShutdownThreadPoolWithInterruptedException() throws InterruptedException {
|
||||
ExecutorService executor = mock(ExecutorService.class);
|
||||
when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException());
|
||||
ThreadUtils.shutdownThreadPool(executor);
|
||||
verify(executor, times(4)).shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testShutdownThreadPoolWithOtherException() throws InterruptedException {
|
||||
ExecutorService executor = mock(ExecutorService.class);
|
||||
Logger logger = mock(Logger.class);
|
||||
Throwable cause = new RuntimeException();
|
||||
when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(cause);
|
||||
ThreadUtils.shutdownThreadPool(executor, logger);
|
||||
verify(executor).shutdownNow();
|
||||
verify(logger, times(3)).error("ThreadPoolManager shutdown executor has error : ", cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddShutdownHook() {
|
||||
Runnable shutdownHook = () -> {
|
||||
};
|
||||
ThreadUtils.addShutdownHook(shutdownHook);
|
||||
// It seems no way to check it.
|
||||
}
|
||||
}
|
@ -36,6 +36,8 @@ public class TlsTypeResolveTest {
|
||||
|
||||
SslProvider anySsl = TlsTypeResolve.getSslProvider("anySSL");
|
||||
Assert.assertEquals(SslProvider.OPENSSL, anySsl);
|
||||
|
||||
|
||||
SslProvider refcnt = TlsTypeResolve.getSslProvider("openSSL_refcnt");
|
||||
Assert.assertEquals(SslProvider.OPENSSL_REFCNT, refcnt);
|
||||
}
|
||||
}
|
||||
|
@ -20,6 +20,7 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ -34,9 +35,38 @@ public class TypeUtilsTest {
|
||||
public void parameterize() {
|
||||
ParameterizedType stringComparableType = TypeUtils.parameterize(List.class, String.class);
|
||||
Assert.assertEquals("java.util.List<java.lang.String>", stringComparableType.toString());
|
||||
Assert.assertEquals(List.class, stringComparableType.getRawType());
|
||||
Assert.assertNull(stringComparableType.getOwnerType());
|
||||
Assert.assertEquals(1, stringComparableType.getActualTypeArguments().length);
|
||||
Assert.assertEquals(String.class, stringComparableType.getActualTypeArguments()[0]);
|
||||
|
||||
ParameterizedType stringIntegerComparableType = TypeUtils.parameterize(Map.class, String.class, Integer.class);
|
||||
Assert.assertEquals("java.util.Map<java.lang.String, java.lang.Integer>",
|
||||
stringIntegerComparableType.toString());
|
||||
Assert.assertEquals(Map.class, stringIntegerComparableType.getRawType());
|
||||
Assert.assertNull(stringComparableType.getOwnerType());
|
||||
Assert.assertEquals(2, stringIntegerComparableType.getActualTypeArguments().length);
|
||||
Assert.assertEquals(String.class, stringIntegerComparableType.getActualTypeArguments()[0]);
|
||||
Assert.assertEquals(Integer.class, stringIntegerComparableType.getActualTypeArguments()[1]);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testParameterizeForNull() {
|
||||
TypeUtils.parameterize(null, String.class);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testParameterizeForNullType() {
|
||||
TypeUtils.parameterize(List.class, (Type[]) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testParameterizeForNullTypeArray() {
|
||||
TypeUtils.parameterize(List.class, (Type) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testParameterizeForDiffLength() {
|
||||
TypeUtils.parameterize(List.class, String.class, Integer.class);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UuidUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testGenerateUuid() {
|
||||
String uuid = UuidUtils.generateUuid();
|
||||
// try parse to UUID.
|
||||
UUID.fromString(uuid);
|
||||
}
|
||||
}
|
@ -87,4 +87,9 @@ public class VersionUtilsTest {
|
||||
VersionUtils.compareVersion("1.2.1.1", "1.2.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFullClientVersion() {
|
||||
Assert.assertNotNull(VersionUtils.getFullClientVersion());
|
||||
Assert.assertTrue(VersionUtils.getFullClientVersion().startsWith("Nacos-Java-Client:v"));
|
||||
}
|
||||
}
|
17
common/src/test/resources/resource_utils_test.properties
Normal file
17
common/src/test/resources/resource_utils_test.properties
Normal file
@ -0,0 +1,17 @@
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
a=b
|
Loading…
Reference in New Issue
Block a user