index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext8_add | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext8_add/impl/AddExt2Impl1.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.ext8_add.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ext8_add.AddExt2;
public class AddExt2Impl1 implements AddExt2 {
public String echo(URL url, String s) {
return this.getClass().getSimpleName();
}
}
| 6,400 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext11_no_adaptive/NoAdaptiveExt.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.ext11_no_adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* Has no Adaptive annotation
*/
@SPI
public interface NoAdaptiveExt {
String echo(String s);
}
| 6,401 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext11_no_adaptive/NoAdaptiveExtImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.ext11_no_adaptive;
public class NoAdaptiveExtImpl implements NoAdaptiveExt {
public String echo(String s) {
return "NoAdaptiveExtImpl-echo";
}
}
| 6,402 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.adaptive;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface HasAdaptiveExt {
@Adaptive
String echo(URL url, String s);
}
| 6,403 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.adaptive.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt;
@Adaptive
public class HasAdaptiveExt_ManualAdaptive implements HasAdaptiveExt {
public String echo(URL url, String s) {
HasAdaptiveExt addExt1 =
ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key"));
return addExt1.echo(url, s);
}
}
| 6,404 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExtImpl1.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.adaptive.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt;
public class HasAdaptiveExtImpl1 implements HasAdaptiveExt {
public String echo(URL url, String s) {
return this.getClass().getSimpleName();
}
}
| 6,405 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2BooleanConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.convert;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.StringToBooleanConverter;
/**
* A {@link Converter} implementation of {@linkg String} to {@link Boolean}
*
* @since 2.7.7
*/
public class String2BooleanConverter extends StringToBooleanConverter {}
| 6,406 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2DoubleConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.convert;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.StringToDoubleConverter;
/**
* A {@link Converter} implementation of {@linkg String} to {@link Double}
*
* @since 2.7.7
*/
public class String2DoubleConverter extends StringToDoubleConverter {}
| 6,407 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2IntegerConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.extension.convert;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.StringToIntegerConverter;
/**
* A {@link Converter} implementation of {@linkg String} to {@link Integer}
*
* @since 2.7.7
*/
public class String2IntegerConverter extends StringToIntegerConverter {}
| 6,408 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger;
import org.apache.dubbo.common.logger.jcl.JclLogger;
import org.apache.dubbo.common.logger.jcl.JclLoggerAdapter;
import org.apache.dubbo.common.logger.jdk.JdkLogger;
import org.apache.dubbo.common.logger.jdk.JdkLoggerAdapter;
import org.apache.dubbo.common.logger.log4j.Log4jLogger;
import org.apache.dubbo.common.logger.log4j.Log4jLoggerAdapter;
import org.apache.dubbo.common.logger.log4j2.Log4j2Logger;
import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter;
import org.apache.dubbo.common.logger.slf4j.Slf4jLogger;
import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter;
import java.lang.reflect.InvocationTargetException;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class LoggerAdapterTest {
static Stream<Arguments> data() {
return Stream.of(
Arguments.of(JclLoggerAdapter.class, JclLogger.class),
Arguments.of(JdkLoggerAdapter.class, JdkLogger.class),
Arguments.of(Log4jLoggerAdapter.class, Log4jLogger.class),
Arguments.of(Slf4jLoggerAdapter.class, Slf4jLogger.class),
Arguments.of(Log4j2LoggerAdapter.class, Log4j2Logger.class));
}
@ParameterizedTest
@MethodSource("data")
void testGetLogger(Class<? extends LoggerAdapter> loggerAdapterClass, Class<? extends Logger> loggerClass)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
LoggerAdapter loggerAdapter =
loggerAdapterClass.getDeclaredConstructor().newInstance();
Logger logger = loggerAdapter.getLogger(this.getClass());
assertThat(logger.getClass().isAssignableFrom(loggerClass), is(true));
logger = loggerAdapter.getLogger(this.getClass().getSimpleName());
assertThat(logger.getClass().isAssignableFrom(loggerClass), is(true));
}
@ParameterizedTest
@MethodSource("data")
void testLevel(Class<? extends LoggerAdapter> loggerAdapterClass)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
LoggerAdapter loggerAdapter =
loggerAdapterClass.getDeclaredConstructor().newInstance();
for (Level targetLevel : Level.values()) {
loggerAdapter.setLevel(targetLevel);
assertThat(loggerAdapter.getLevel(), is(targetLevel));
}
}
}
| 6,409 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.File;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
class LoggerFactoryTest {
@Test
void testLoggerLevel() {
LoggerFactory.setLevel(Level.INFO);
Level level = LoggerFactory.getLevel();
assertThat(level, is(Level.INFO));
}
@Test
void testGetLogFile() {
LoggerFactory.setLoggerAdapter(FrameworkModel.defaultModel(), "slf4j");
File file = LoggerFactory.getFile();
assertThat(file, is(nullValue()));
}
@Test
void testAllLogLevel() {
for (Level targetLevel : Level.values()) {
LoggerFactory.setLevel(targetLevel);
Level level = LoggerFactory.getLevel();
assertThat(level, is(targetLevel));
}
}
@Test
void testGetLogger() {
Logger logger1 = LoggerFactory.getLogger(this.getClass());
Logger logger2 = LoggerFactory.getLogger(this.getClass());
assertThat(logger1, is(logger2));
}
@Test
void shouldReturnSameLogger() {
Logger logger1 = LoggerFactory.getLogger(this.getClass().getName());
Logger logger2 = LoggerFactory.getLogger(this.getClass().getName());
assertThat(logger1, is(logger2));
}
@Test
void shouldReturnSameErrorTypeAwareLogger() {
ErrorTypeAwareLogger logger1 =
LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName());
ErrorTypeAwareLogger logger2 =
LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName());
assertThat(logger1, is(logger2));
}
}
| 6,410 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger;
import org.apache.dubbo.common.logger.jcl.JclLoggerAdapter;
import org.apache.dubbo.common.logger.jdk.JdkLoggerAdapter;
import org.apache.dubbo.common.logger.log4j.Log4jLoggerAdapter;
import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter;
import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter;
import java.lang.reflect.InvocationTargetException;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
class LoggerTest {
static Stream<Arguments> data() {
return Stream.of(
Arguments.of(JclLoggerAdapter.class),
Arguments.of(JdkLoggerAdapter.class),
Arguments.of(Log4jLoggerAdapter.class),
Arguments.of(Slf4jLoggerAdapter.class),
Arguments.of(Log4j2LoggerAdapter.class));
}
@ParameterizedTest
@MethodSource("data")
void testAllLogMethod(Class<? extends LoggerAdapter> loggerAdapter) throws Exception {
LoggerAdapter adapter = loggerAdapter.getDeclaredConstructor().newInstance();
adapter.setLevel(Level.ALL);
Logger logger = adapter.getLogger(this.getClass());
logger.error("error");
logger.warn("warn");
logger.info("info");
logger.debug("debug");
logger.trace("info");
logger.error(new Exception("error"));
logger.warn(new Exception("warn"));
logger.info(new Exception("info"));
logger.debug(new Exception("debug"));
logger.trace(new Exception("trace"));
logger.error("error", new Exception("error"));
logger.warn("warn", new Exception("warn"));
logger.info("info", new Exception("info"));
logger.debug("debug", new Exception("debug"));
logger.trace("trace", new Exception("trace"));
}
@ParameterizedTest
@MethodSource("data")
void testLevelEnable(Class<? extends LoggerAdapter> loggerAdapter)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
LoggerAdapter adapter = loggerAdapter.getDeclaredConstructor().newInstance();
adapter.setLevel(Level.ALL);
Logger logger = adapter.getLogger(this.getClass());
assertThat(logger.isWarnEnabled(), not(nullValue()));
assertThat(logger.isTraceEnabled(), not(nullValue()));
assertThat(logger.isErrorEnabled(), not(nullValue()));
assertThat(logger.isInfoEnabled(), not(nullValue()));
assertThat(logger.isDebugEnabled(), not(nullValue()));
}
}
| 6,411 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger.slf4j;
import org.junit.jupiter.api.Test;
import org.slf4j.spi.LocationAwareLogger;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
class Slf4jLoggerTest {
@Test
void testLocationAwareLogger() {
LocationAwareLogger locationAwareLogger = mock(LocationAwareLogger.class);
Slf4jLogger logger = new Slf4jLogger(locationAwareLogger);
logger.error("error");
logger.warn("warn");
logger.info("info");
logger.debug("debug");
logger.trace("info");
verify(locationAwareLogger, times(5)).log(isNull(), anyString(), anyInt(), anyString(), isNull(), isNull());
logger.error(new Exception("error"));
logger.warn(new Exception("warn"));
logger.info(new Exception("info"));
logger.debug(new Exception("debug"));
logger.trace(new Exception("trace"));
logger.error("error", new Exception("error"));
logger.warn("warn", new Exception("warn"));
logger.info("info", new Exception("info"));
logger.debug("debug", new Exception("debug"));
logger.trace("trace", new Exception("trace"));
verify(locationAwareLogger, times(10))
.log(isNull(), anyString(), anyInt(), anyString(), isNull(), any(Throwable.class));
}
}
| 6,412 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger.support;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ADDRESS_INVALID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for FailsafeErrorTypeAwareLogger to test whether it 'ignores' exceptions thrown by logger or not.
*/
class FailsafeErrorTypeAwareLoggerTest {
@Test
void testFailsafeErrorTypeAwareForLoggingMethod() {
Logger failLogger = mock(Logger.class);
FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger);
doThrow(new RuntimeException()).when(failLogger).error(anyString());
doThrow(new RuntimeException()).when(failLogger).warn(anyString());
doThrow(new RuntimeException()).when(failLogger).info(anyString());
doThrow(new RuntimeException()).when(failLogger).debug(anyString());
doThrow(new RuntimeException()).when(failLogger).trace(anyString());
failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error");
failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn");
doThrow(new RuntimeException()).when(failLogger).error(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).warn(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).info(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).debug(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).trace(any(Throwable.class));
failsafeLogger.error(
REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error"));
failsafeLogger.warn(
REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn"));
}
@Test
void testSuccessLogger() {
Logger successLogger = mock(Logger.class);
FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(successLogger);
failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error");
failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn");
verify(successLogger).error(anyString());
verify(successLogger).warn(anyString());
failsafeLogger.error(
REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error"));
failsafeLogger.warn(
REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn"));
}
@Test
void testGetLogger() {
Assertions.assertThrows(RuntimeException.class, () -> {
Logger failLogger = mock(Logger.class);
FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger);
doThrow(new RuntimeException()).when(failLogger).error(anyString());
failsafeLogger.getLogger().error("should get error");
});
}
@Test
void testInstructionShownOrNot() {
LoggerFactory.setLoggerAdapter(FrameworkModel.defaultModel(), "jdk");
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailsafeErrorTypeAwareLoggerTest.class);
logger.error(
REGISTRY_ADDRESS_INVALID,
"Registry center",
"May be it's offline.",
"error message",
new Exception("error"));
logger.error(
REGISTRY_ADDRESS_INVALID,
"Registry center",
"May be it's offline.",
"error message",
new Exception("error"));
}
}
| 6,413 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.logger.support;
import org.apache.dubbo.common.logger.Logger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class FailsafeLoggerTest {
@Test
void testFailSafeForLoggingMethod() {
Logger failLogger = mock(Logger.class);
FailsafeLogger failsafeLogger = new FailsafeLogger(failLogger);
doThrow(new RuntimeException()).when(failLogger).error(anyString());
doThrow(new RuntimeException()).when(failLogger).warn(anyString());
doThrow(new RuntimeException()).when(failLogger).info(anyString());
doThrow(new RuntimeException()).when(failLogger).debug(anyString());
doThrow(new RuntimeException()).when(failLogger).trace(anyString());
failsafeLogger.error("error");
failsafeLogger.warn("warn");
failsafeLogger.info("info");
failsafeLogger.debug("debug");
failsafeLogger.trace("info");
doThrow(new RuntimeException()).when(failLogger).error(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).warn(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).info(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).debug(any(Throwable.class));
doThrow(new RuntimeException()).when(failLogger).trace(any(Throwable.class));
failsafeLogger.error(new Exception("error"));
failsafeLogger.warn(new Exception("warn"));
failsafeLogger.info(new Exception("info"));
failsafeLogger.debug(new Exception("debug"));
failsafeLogger.trace(new Exception("trace"));
failsafeLogger.error("error", new Exception("error"));
failsafeLogger.warn("warn", new Exception("warn"));
failsafeLogger.info("info", new Exception("info"));
failsafeLogger.debug("debug", new Exception("debug"));
failsafeLogger.trace("trace", new Exception("trace"));
}
@Test
void testSuccessLogger() {
Logger successLogger = mock(Logger.class);
FailsafeLogger failsafeLogger = new FailsafeLogger(successLogger);
failsafeLogger.error("error");
failsafeLogger.warn("warn");
failsafeLogger.info("info");
failsafeLogger.debug("debug");
failsafeLogger.trace("info");
verify(successLogger).error(anyString());
verify(successLogger).warn(anyString());
verify(successLogger).info(anyString());
verify(successLogger).debug(anyString());
verify(successLogger).trace(anyString());
failsafeLogger.error(new Exception("error"));
failsafeLogger.warn(new Exception("warn"));
failsafeLogger.info(new Exception("info"));
failsafeLogger.debug(new Exception("debug"));
failsafeLogger.trace(new Exception("trace"));
failsafeLogger.error("error", new Exception("error"));
failsafeLogger.warn("warn", new Exception("warn"));
failsafeLogger.info("info", new Exception("info"));
failsafeLogger.debug("debug", new Exception("debug"));
failsafeLogger.trace("trace", new Exception("trace"));
}
@Test
void testGetLogger() {
Assertions.assertThrows(RuntimeException.class, () -> {
Logger failLogger = mock(Logger.class);
FailsafeLogger failsafeLogger = new FailsafeLogger(failLogger);
doThrow(new RuntimeException()).when(failLogger).error(anyString());
failsafeLogger.getLogger().error("should get error");
});
}
}
| 6,414 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.cache;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FileCacheStoreTest {
private FileCacheStore cacheStore;
@Test
void testCache() throws Exception {
String directoryPath = getDirectoryOfClassPath();
String filePath = "test-cache.dubbo.cache";
cacheStore = FileCacheStoreFactory.getInstance(directoryPath, filePath);
Map<String, String> properties = cacheStore.loadCache(10);
assertEquals(2, properties.size());
Map<String, String> newProperties = new HashMap<>();
newProperties.put("newKey1", "newValue1");
newProperties.put("newKey2", "newValue2");
newProperties.put("newKey3", "newValue3");
newProperties.put("newKey4", "newValue4");
cacheStore = FileCacheStoreFactory.getInstance(directoryPath, "non-exit.dubbo.cache");
cacheStore.refreshCache(newProperties, "test refresh cache", 0);
Map<String, String> propertiesLimitTo2 = cacheStore.loadCache(2);
assertEquals(2, propertiesLimitTo2.size());
Map<String, String> propertiesLimitTo10 = cacheStore.loadCache(10);
assertEquals(4, propertiesLimitTo10.size());
cacheStore.destroy();
}
@Test
void testFileSizeExceed() throws Exception {
String directoryPath = getDirectoryOfClassPath();
Map<String, String> newProperties = new HashMap<>();
newProperties.put("newKey1", "newValue1");
newProperties.put("newKey2", "newValue2");
newProperties.put("newKey3", "newValue3");
newProperties.put("newKey4", "newValue4");
cacheStore = FileCacheStoreFactory.getInstance(directoryPath, "non-exit.dubbo.cache");
cacheStore.refreshCache(newProperties, "test refresh cache", 2);
Map<String, String> propertiesLimitTo1 = cacheStore.loadCache(2);
assertEquals(0, propertiesLimitTo1.size());
}
private String getDirectoryOfClassPath() throws URISyntaxException {
URL resource = this.getClass().getResource("/log4j.xml");
String path = Paths.get(resource.toURI()).toFile().getAbsolutePath();
int index = path.indexOf("log4j.xml");
String directoryPath = path.substring(0, index);
return directoryPath;
}
}
| 6,415 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.cache;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class FileCacheStoreFactoryTest {
@Test
void testSafeName() throws URISyntaxException {
FileCacheStore store1 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "../../../dubbo");
Assertions.assertEquals(
getDirectoryOfClassPath() + "..%002f..%002f..%002fdubbo.dubbo.cache", store1.getCacheFilePath());
store1.destroy();
FileCacheStore store2 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "../../../中文");
Assertions.assertEquals(
getDirectoryOfClassPath() + "..%002f..%002f..%002f%4e2d%6587.dubbo.cache", store2.getCacheFilePath());
store2.destroy();
}
@Test
void testPathIsFile() throws URISyntaxException, IOException {
String basePath = getDirectoryOfClassPath();
String filePath = basePath + File.separator + "isFile";
new File(filePath).createNewFile();
Assertions.assertThrows(RuntimeException.class, () -> FileCacheStoreFactory.getInstance(filePath, "dubbo"));
}
@Test
void testCacheContains() throws URISyntaxException {
FileCacheStore store1 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "testCacheContains");
Assertions.assertNotNull(store1.getCacheFilePath());
FileCacheStoreFactory.getCacheMap().remove(store1.getCacheFilePath());
FileCacheStore store2 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "testCacheContains");
Assertions.assertEquals(FileCacheStore.Empty.class, store2.getClass());
store1.destroy();
store2.destroy();
FileCacheStore store3 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "testCacheContains");
Assertions.assertNotNull(store3.getCacheFilePath());
store3.destroy();
}
private String getDirectoryOfClassPath() throws URISyntaxException {
URL resource = this.getClass().getResource("/log4j.xml");
String path = Paths.get(resource.toURI()).toFile().getAbsolutePath();
int index = path.indexOf("log4j.xml");
String directoryPath = path.substring(0, index);
return directoryPath;
}
}
| 6,416 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link CompositeConfiguration}
*/
class CompositeConfigurationTest {
@Test
void test() {
InmemoryConfiguration inmemoryConfiguration1 = new InmemoryConfiguration();
InmemoryConfiguration inmemoryConfiguration2 = new InmemoryConfiguration();
InmemoryConfiguration inmemoryConfiguration3 = new InmemoryConfiguration();
CompositeConfiguration configuration = new CompositeConfiguration(new Configuration[] {inmemoryConfiguration1});
configuration.addConfiguration(inmemoryConfiguration2);
configuration.addConfigurationFirst(inmemoryConfiguration3);
inmemoryConfiguration1.addProperty("k", "v1");
inmemoryConfiguration2.addProperty("k", "v2");
inmemoryConfiguration3.addProperty("k", "v3");
Assertions.assertEquals(configuration.getInternalProperty("k"), "v3");
}
}
| 6,417 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* The type Environment configuration test.
*/
class EnvironmentConfigurationTest {
private static final String MOCK_KEY = "DUBBO_KEY";
private static final String MOCK_VALUE = "mockValue";
@Test
void testGetInternalProperty() {
Map<String, String> map = new HashMap<>();
map.put(MOCK_KEY, MOCK_VALUE);
EnvironmentConfiguration configuration = new EnvironmentConfiguration() {
@Override
protected String getenv(String key) {
return map.get(key);
}
};
// this UT maybe only works on particular platform, assert only when value is not null.
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("dubbo.key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("dubbo_key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty(MOCK_KEY));
}
@Test
void testGetProperties() {
Map<String, String> map = new HashMap<>();
map.put(MOCK_KEY, MOCK_VALUE);
EnvironmentConfiguration configuration = new EnvironmentConfiguration() {
@Override
protected Map<String, String> getenv() {
return map;
}
};
Assertions.assertEquals(map, configuration.getProperties());
}
}
| 6,418 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link PropertiesConfiguration}
*/
class PropertiesConfigurationTest {
@Test
void test() {
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration(ApplicationModel.defaultModel());
Map<String, String> properties = propertiesConfiguration.getProperties();
Assertions.assertEquals(properties.get("dubbo"), "properties");
Assertions.assertEquals(properties.get("dubbo.application.enable-file-cache"), "false");
Assertions.assertEquals(properties.get("dubbo.service.shutdown.wait"), "200");
Assertions.assertEquals(propertiesConfiguration.getProperty("dubbo"), "properties");
Assertions.assertEquals(propertiesConfiguration.getInternalProperty("dubbo"), "properties");
propertiesConfiguration.setProperty("k1", "v1");
Assertions.assertEquals(propertiesConfiguration.getProperty("k1"), "v1");
propertiesConfiguration.remove("k1");
Assertions.assertNull(propertiesConfiguration.getProperty("k1"));
}
}
| 6,419 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
/**
*
*/
class ConfigurationUtilsTest {
@Test
void testCachedProperties() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
Environment originApplicationEnvironment = applicationModel.modelEnvironment();
Environment applicationEnvironment = Mockito.spy(originApplicationEnvironment);
applicationModel.setEnvironment(applicationEnvironment);
Configuration configuration = Mockito.mock(Configuration.class);
Mockito.when(applicationEnvironment.getDynamicGlobalConfiguration()).thenReturn(configuration);
Mockito.when(configuration.getString("TestKey", "")).thenReturn("a");
Assertions.assertEquals("a", ConfigurationUtils.getCachedDynamicProperty(applicationModel, "TestKey", "xxx"));
Mockito.when(configuration.getString("TestKey", "")).thenReturn("b");
// cached key
Assertions.assertEquals("a", ConfigurationUtils.getCachedDynamicProperty(applicationModel, "TestKey", "xxx"));
ModuleModel moduleModel = applicationModel.newModule();
ModuleEnvironment originModuleEnvironment = moduleModel.modelEnvironment();
ModuleEnvironment moduleEnvironment = Mockito.spy(originModuleEnvironment);
moduleModel.setModuleEnvironment(moduleEnvironment);
Mockito.when(moduleEnvironment.getDynamicGlobalConfiguration()).thenReturn(configuration);
// ApplicationModel should not affect ModuleModel
Assertions.assertEquals("b", ConfigurationUtils.getCachedDynamicProperty(moduleModel, "TestKey", "xxx"));
Mockito.when(configuration.getString("TestKey", "")).thenReturn("c");
// cached key
Assertions.assertEquals("b", ConfigurationUtils.getCachedDynamicProperty(moduleModel, "TestKey", "xxx"));
moduleModel.setModuleEnvironment(originModuleEnvironment);
applicationModel.setEnvironment(originApplicationEnvironment);
frameworkModel.destroy();
}
@Test
void testGetServerShutdownTimeout() {
System.setProperty(SHUTDOWN_WAIT_KEY, " 10000");
Assertions.assertEquals(10000, ConfigurationUtils.getServerShutdownTimeout(ApplicationModel.defaultModel()));
System.clearProperty(SHUTDOWN_WAIT_KEY);
}
@Test
void testGetProperty() {
System.setProperty(SHUTDOWN_WAIT_KEY, " 10000");
Assertions.assertEquals(
"10000", ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), SHUTDOWN_WAIT_KEY));
System.clearProperty(SHUTDOWN_WAIT_KEY);
}
@Test
void testParseSingleProperties() throws Exception {
String p1 = "aaa=bbb";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(1, result.size());
Assertions.assertEquals("bbb", result.get("aaa"));
}
@Test
void testParseMultipleProperties() throws Exception {
String p1 = "aaa=bbb\nccc=ddd";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(2, result.size());
Assertions.assertEquals("bbb", result.get("aaa"));
Assertions.assertEquals("ddd", result.get("ccc"));
}
@Test
void testEscapedNewLine() throws Exception {
String p1 = "dubbo.registry.address=zookeeper://127.0.0.1:2181\\\\ndubbo.protocol.port=20880";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(1, result.size());
Assertions.assertEquals(
"zookeeper://127.0.0.1:2181\\ndubbo.protocol.port=20880", result.get("dubbo.registry.address"));
}
}
| 6,420 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider1.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.Properties;
public class MockOrderedPropertiesProvider1 implements OrderedPropertiesProvider {
@Override
public int priority() {
return 3;
}
@Override
public Properties initProperties() {
Properties properties = new Properties();
properties.put("testKey", "333");
return properties;
}
}
| 6,421 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link OrderedPropertiesConfiguration}
*/
class OrderedPropertiesConfigurationTest {
@Test
void testOrderPropertiesProviders() {
OrderedPropertiesConfiguration configuration = new OrderedPropertiesConfiguration(
ApplicationModel.defaultModel().getDefaultModule());
Assertions.assertEquals("999", configuration.getInternalProperty("testKey"));
}
}
| 6,422 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.beanutil.JavaBeanAccessor;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test of class InmemoryConfiguration, and interface Configuration.
*/
class InmemoryConfigurationTest {
private InmemoryConfiguration memConfig;
private static final String MOCK_KEY = "mockKey";
private static final String MOCK_VALUE = "mockValue";
private static final String MOCK_ONE_KEY = "one";
private static final String MOCK_TWO_KEY = "two";
private static final String MOCK_THREE_KEY = "three";
/**
* Init.
*/
@BeforeEach
public void init() {
memConfig = new InmemoryConfiguration();
}
/**
* Test get mem property.
*/
@Test
void testGetMemProperty() {
Assertions.assertNull(memConfig.getInternalProperty(MOCK_KEY));
Assertions.assertFalse(memConfig.containsKey(MOCK_KEY));
Assertions.assertNull(memConfig.getString(MOCK_KEY));
Assertions.assertNull(memConfig.getProperty(MOCK_KEY));
memConfig.addProperty(MOCK_KEY, MOCK_VALUE);
Assertions.assertTrue(memConfig.containsKey(MOCK_KEY));
Assertions.assertEquals(MOCK_VALUE, memConfig.getInternalProperty(MOCK_KEY));
Assertions.assertEquals(MOCK_VALUE, memConfig.getString(MOCK_KEY, MOCK_VALUE));
Assertions.assertEquals(MOCK_VALUE, memConfig.getProperty(MOCK_KEY, MOCK_VALUE));
}
/**
* Test get properties.
*/
@Test
void testGetProperties() {
Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
Map<String, String> proMap = new HashMap<>();
proMap.put(MOCK_ONE_KEY, MOCK_VALUE);
proMap.put(MOCK_TWO_KEY, MOCK_VALUE);
memConfig.addProperties(proMap);
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
Map<String, String> anotherProMap = new HashMap<>();
anotherProMap.put(MOCK_THREE_KEY, MOCK_VALUE);
memConfig.setProperties(anotherProMap);
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_THREE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
}
@Test
void testGetInt() {
memConfig.addProperty("a", "1");
Assertions.assertEquals(1, memConfig.getInt("a"));
Assertions.assertEquals(Integer.valueOf(1), memConfig.getInteger("a", 2));
Assertions.assertEquals(2, memConfig.getInt("b", 2));
}
@Test
void getBoolean() {
memConfig.addProperty("a", Boolean.TRUE.toString());
Assertions.assertTrue(memConfig.getBoolean("a"));
Assertions.assertFalse(memConfig.getBoolean("b", false));
Assertions.assertTrue(memConfig.getBoolean("b", Boolean.TRUE));
}
@Test
void testIllegalType() {
memConfig.addProperty("it", "aaa");
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInteger("it", 1));
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInt("it", 1));
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInt("it"));
}
@Test
void testDoesNotExist() {
Assertions.assertThrows(NoSuchElementException.class, () -> memConfig.getInt("ne"));
Assertions.assertThrows(NoSuchElementException.class, () -> memConfig.getBoolean("ne"));
}
@Test
void testConversions() {
memConfig.addProperty("long", "2147483648");
memConfig.addProperty("byte", "127");
memConfig.addProperty("short", "32767");
memConfig.addProperty("float", "3.14");
memConfig.addProperty("double", "3.14159265358979323846264338327950");
memConfig.addProperty("enum", "FIELD");
Object longObject = memConfig.convert(Long.class, "long", 1L);
Object byteObject = memConfig.convert(Byte.class, "byte", (byte) 1);
Object shortObject = memConfig.convert(Short.class, "short", (short) 1);
Object floatObject = memConfig.convert(Float.class, "float", 3.14F);
Object doubleObject = memConfig.convert(Double.class, "double", 3.14159265358979323846264338327950);
JavaBeanAccessor javaBeanAccessor = memConfig.convert(JavaBeanAccessor.class, "enum", JavaBeanAccessor.ALL);
Assertions.assertEquals(Long.class, longObject.getClass());
Assertions.assertEquals(2147483648L, longObject);
Assertions.assertEquals(Byte.class, byteObject.getClass());
Assertions.assertEquals((byte) 127, byteObject);
Assertions.assertEquals(Short.class, shortObject.getClass());
Assertions.assertEquals((short) 32767, shortObject);
Assertions.assertEquals(Float.class, floatObject.getClass());
Assertions.assertEquals(3.14F, floatObject);
Assertions.assertEquals(Double.class, doubleObject.getClass());
Assertions.assertEquals(3.14159265358979323846264338327950, doubleObject);
Assertions.assertEquals(JavaBeanAccessor.class, javaBeanAccessor.getClass());
Assertions.assertEquals(JavaBeanAccessor.FIELD, javaBeanAccessor);
}
/**
* Clean.
*/
@AfterEach
public void clean() {}
}
| 6,423 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.Properties;
public class MockOrderedPropertiesProvider2 implements OrderedPropertiesProvider {
@Override
public int priority() {
return 1;
}
@Override
public Properties initProperties() {
Properties properties = new Properties();
properties.put("testKey", "999");
return properties;
}
}
| 6,424 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class PrefixedConfigurationTest {
@Test
void testPrefixedConfiguration() {
Map<String, String> props = new LinkedHashMap<>();
props.put("dubbo.protocol.name", "dubbo");
props.put("dubbo.protocol.port", "1234");
props.put("dubbo.protocols.rest.port", "2345");
InmemoryConfiguration inmemoryConfiguration = new InmemoryConfiguration();
inmemoryConfiguration.addProperties(props);
// prefixed over InmemoryConfiguration
PrefixedConfiguration prefixedConfiguration =
new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocol");
Assertions.assertEquals("dubbo", prefixedConfiguration.getProperty("name"));
Assertions.assertEquals("1234", prefixedConfiguration.getProperty("port"));
prefixedConfiguration = new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocols.rest");
Assertions.assertEquals("2345", prefixedConfiguration.getProperty("port"));
// prefixed over composite configuration
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(inmemoryConfiguration);
prefixedConfiguration = new PrefixedConfiguration(compositeConfiguration, "dubbo.protocols.rest");
Assertions.assertEquals("2345", prefixedConfiguration.getProperty("port"));
}
}
| 6,425 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link Environment}
*/
class EnvironmentTest {
@Test
void testResolvePlaceholders() {
Environment environment = ApplicationModel.defaultModel().modelEnvironment();
Map<String, String> externalMap = new LinkedHashMap<>();
externalMap.put("zookeeper.address", "127.0.0.1");
externalMap.put("zookeeper.port", "2181");
environment.updateAppExternalConfigMap(externalMap);
Map<String, String> sysprops = new LinkedHashMap<>();
sysprops.put("zookeeper.address", "192.168.10.1");
System.getProperties().putAll(sysprops);
try {
String s = environment.resolvePlaceholders("zookeeper://${zookeeper.address}:${zookeeper.port}");
assertEquals("zookeeper://192.168.10.1:2181", s);
} finally {
for (String key : sysprops.keySet()) {
System.clearProperty(key);
}
}
}
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
Environment environment = applicationModel.modelEnvironment();
// test getPrefixedConfiguration
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("127.0.0.1");
registryConfig.setPort(2181);
String prefix = "dubbo.registry";
Configuration prefixedConfiguration = environment.getPrefixedConfiguration(registryConfig, prefix);
Assertions.assertTrue(prefixedConfiguration instanceof PrefixedConfiguration);
// test getConfigurationMaps(AbstractConfig config, String prefix)
List<Map<String, String>> configurationMaps = environment.getConfigurationMaps(registryConfig, prefix);
Assertions.assertEquals(7, configurationMaps.size());
// test getConfigurationMaps()
configurationMaps = environment.getConfigurationMaps();
Assertions.assertEquals(6, configurationMaps.size());
CompositeConfiguration configuration1 = environment.getConfiguration();
CompositeConfiguration configuration2 = environment.getConfiguration();
Assertions.assertEquals(configuration1, configuration2);
// test getDynamicConfiguration
Optional<DynamicConfiguration> dynamicConfiguration = environment.getDynamicConfiguration();
Assertions.assertFalse(dynamicConfiguration.isPresent());
// test getDynamicGlobalConfiguration
Configuration dynamicGlobalConfiguration = environment.getDynamicGlobalConfiguration();
Assertions.assertEquals(dynamicGlobalConfiguration, configuration1);
CompositeDynamicConfiguration compositeDynamicConfiguration = new CompositeDynamicConfiguration();
environment.setDynamicConfiguration(compositeDynamicConfiguration);
dynamicConfiguration = environment.getDynamicConfiguration();
Assertions.assertEquals(dynamicConfiguration.get(), compositeDynamicConfiguration);
dynamicGlobalConfiguration = environment.getDynamicGlobalConfiguration();
Assertions.assertNotEquals(dynamicGlobalConfiguration, configuration1);
// test destroy
environment.destroy();
Assertions.assertNull(environment.getSystemConfiguration());
Assertions.assertNull(environment.getEnvironmentConfiguration());
Assertions.assertNull(environment.getAppExternalConfiguration());
Assertions.assertNull(environment.getExternalConfiguration());
Assertions.assertNull(environment.getAppConfiguration());
frameworkModel.destroy();
}
}
| 6,426 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link ConfigurationCache}
*/
class ConfigurationCacheTest {
@Test
void test() {
ConfigurationCache configurationCache = new ConfigurationCache();
String value = configurationCache.computeIfAbsent("k1", k -> "v1");
Assertions.assertEquals(value, "v1");
value = configurationCache.computeIfAbsent("k1", k -> "v2");
Assertions.assertEquals(value, "v1");
}
}
| 6,427 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The type System configuration test.
*/
class SystemConfigurationTest {
private static SystemConfiguration sysConfig;
private static final String MOCK_KEY = "mockKey";
private static final String MOCK_STRING_VALUE = "mockValue";
private static final Boolean MOCK_BOOL_VALUE = Boolean.FALSE;
private static final Integer MOCK_INT_VALUE = Integer.MAX_VALUE;
private static final Long MOCK_LONG_VALUE = Long.MIN_VALUE;
private static final Short MOCK_SHORT_VALUE = Short.MIN_VALUE;
private static final Float MOCK_FLOAT_VALUE = Float.MIN_VALUE;
private static final Double MOCK_DOUBLE_VALUE = Double.MIN_VALUE;
private static final Byte MOCK_BYTE_VALUE = Byte.MIN_VALUE;
private static final String NOT_EXIST_KEY = "NOTEXIST";
/**
* Init.
*/
@BeforeEach
public void init() {
sysConfig = new SystemConfiguration();
}
/**
* Test get sys property.
*/
@Test
void testGetSysProperty() {
Assertions.assertNull(sysConfig.getInternalProperty(MOCK_KEY));
Assertions.assertFalse(sysConfig.containsKey(MOCK_KEY));
Assertions.assertNull(sysConfig.getString(MOCK_KEY));
Assertions.assertNull(sysConfig.getProperty(MOCK_KEY));
System.setProperty(MOCK_KEY, MOCK_STRING_VALUE);
Assertions.assertTrue(sysConfig.containsKey(MOCK_KEY));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getInternalProperty(MOCK_KEY));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getString(MOCK_KEY, MOCK_STRING_VALUE));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getProperty(MOCK_KEY, MOCK_STRING_VALUE));
}
/**
* Test convert.
*/
@Test
void testConvert() {
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, NOT_EXIST_KEY, MOCK_STRING_VALUE));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_BOOL_VALUE));
Assertions.assertEquals(MOCK_BOOL_VALUE, sysConfig.convert(Boolean.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_STRING_VALUE));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_INT_VALUE));
Assertions.assertEquals(MOCK_INT_VALUE, sysConfig.convert(Integer.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_LONG_VALUE));
Assertions.assertEquals(MOCK_LONG_VALUE, sysConfig.convert(Long.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_SHORT_VALUE));
Assertions.assertEquals(MOCK_SHORT_VALUE, sysConfig.convert(Short.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_FLOAT_VALUE));
Assertions.assertEquals(MOCK_FLOAT_VALUE, sysConfig.convert(Float.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_DOUBLE_VALUE));
Assertions.assertEquals(MOCK_DOUBLE_VALUE, sysConfig.convert(Double.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_BYTE_VALUE));
Assertions.assertEquals(MOCK_BYTE_VALUE, sysConfig.convert(Byte.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(ConfigMock.MockOne));
Assertions.assertEquals(ConfigMock.MockOne, sysConfig.convert(ConfigMock.class, MOCK_KEY, null));
}
/**
* Clean.
*/
@AfterEach
public void clean() {
if (null != System.getProperty(MOCK_KEY)) {
System.clearProperty(MOCK_KEY);
}
}
/**
* The enum Config mock.
*/
enum ConfigMock {
/**
* Mock one config mock.
*/
MockOne,
/**
* Mock two config mock.
*/
MockTwo
}
}
| 6,428 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.ADDED;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.DELETED;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.MODIFIED;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* {@link ConfigChangeType} Test
*
* @see ConfigChangeType
* @since 2.7.5
*/
class ConfigChangeTypeTest {
@Test
void testMembers() {
assertArrayEquals(new ConfigChangeType[] {ADDED, MODIFIED, DELETED}, ConfigChangeType.values());
}
}
| 6,429 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.config.configcenter.nop.NopDynamicConfigurationFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link DynamicConfigurationFactory} Test
*
* @since 2.7.5
*/
class DynamicConfigurationFactoryTest {
@Test
void testDefaultExtension() {
DynamicConfigurationFactory factory =
getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension();
assertEquals(NopDynamicConfigurationFactory.class, factory.getClass());
assertEquals(
NopDynamicConfigurationFactory.class,
getExtensionLoader(DynamicConfigurationFactory.class)
.getExtension("nop")
.getClass());
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> extClass) {
return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(extClass);
}
}
| 6,430 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* {@link ConfigChangedEvent} Test
*
* @since 2.7.5
*/
class ConfigChangedEventTest {
private static final String KEY = "k";
private static final String GROUP = "g";
private static final String CONTENT = "c";
@Test
void testGetter() {
ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT);
assertEquals(KEY, event.getKey());
assertEquals(GROUP, event.getGroup());
assertEquals(CONTENT, event.getContent());
assertEquals(ConfigChangeType.MODIFIED, event.getChangeType());
assertEquals("k,g", event.getSource());
event = new ConfigChangedEvent(KEY, GROUP, CONTENT, ConfigChangeType.ADDED);
assertEquals(KEY, event.getKey());
assertEquals(GROUP, event.getGroup());
assertEquals(CONTENT, event.getContent());
assertEquals(ConfigChangeType.ADDED, event.getChangeType());
assertEquals("k,g", event.getSource());
}
@Test
void testEqualsAndHashCode() {
for (ConfigChangeType type : ConfigChangeType.values()) {
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type));
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode(),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode());
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString(),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString());
}
}
@Test
void testToString() {
ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT);
assertNotNull(event.toString());
}
}
| 6,431 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.nop.NopDynamicConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link AbstractDynamicConfigurationFactory} Test
*
* @see AbstractDynamicConfigurationFactory
* @since 2.7.5
*/
class AbstractDynamicConfigurationFactoryTest {
private AbstractDynamicConfigurationFactory factory;
@BeforeEach
public void init() {
factory = new AbstractDynamicConfigurationFactory() {
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
return new NopDynamicConfiguration(url);
}
};
}
@Test
void testGetDynamicConfiguration() {
URL url = URL.valueOf("nop://127.0.0.1");
assertEquals(factory.getDynamicConfiguration(url), factory.getDynamicConfiguration(url));
}
}
| 6,432 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_PREFIX;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_SIZE;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.GROUP_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.PARAM_NAME_PREFIX;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_PREFIX_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_SIZE_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.TIMEOUT_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* {@link AbstractDynamicConfiguration} Test
*
* @since 2.7.5
*/
class AbstractDynamicConfigurationTest {
private AbstractDynamicConfiguration configuration;
@BeforeEach
public void init() {
configuration = new AbstractDynamicConfiguration(null) {
@Override
protected String doGetConfig(String key, String group) {
return null;
}
@Override
protected void doClose() {}
@Override
protected boolean doRemoveConfig(String key, String group) {
return false;
}
};
}
@Test
void testConstants() {
assertEquals("dubbo.config-center.", PARAM_NAME_PREFIX);
assertEquals("dubbo.config-center.workers", DEFAULT_THREAD_POOL_PREFIX);
assertEquals("dubbo.config-center.thread-pool.prefix", THREAD_POOL_PREFIX_PARAM_NAME);
assertEquals("dubbo.config-center.thread-pool.size", THREAD_POOL_SIZE_PARAM_NAME);
assertEquals("dubbo.config-center.thread-pool.keep-alive-time", THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME);
assertEquals(1, DEFAULT_THREAD_POOL_SIZE);
assertEquals(60 * 1000, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME);
// @since 2.7.8
assertEquals("dubbo.config-center.group", GROUP_PARAM_NAME);
assertEquals("dubbo.config-center.timeout", TIMEOUT_PARAM_NAME);
}
@Test
void testConstructor() {
URL url = URL.valueOf("default://")
.addParameter(THREAD_POOL_PREFIX_PARAM_NAME, "test")
.addParameter(THREAD_POOL_SIZE_PARAM_NAME, 10)
.addParameter(THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME, 100);
AbstractDynamicConfiguration configuration = new AbstractDynamicConfiguration(url) {
@Override
protected String doGetConfig(String key, String group) {
return null;
}
@Override
protected void doClose() {}
@Override
protected boolean doRemoveConfig(String key, String group) {
return false;
}
};
ThreadPoolExecutor threadPoolExecutor = configuration.getWorkersThreadPool();
ThreadFactory threadFactory = threadPoolExecutor.getThreadFactory();
Thread thread = threadFactory.newThread(() -> {});
assertEquals(10, threadPoolExecutor.getCorePoolSize());
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
assertEquals(100, threadPoolExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS));
assertEquals("test-thread-1", thread.getName());
}
@Test
void testPublishConfig() {
assertFalse(configuration.publishConfig(null, null));
assertFalse(configuration.publishConfig(null, null, null));
}
//
// @Test
// public void testGetConfigKeys() {
// assertTrue(configuration.getConfigKeys(null).isEmpty());
// }
@Test
void testGetConfig() {
assertNull(configuration.getConfig(null, null));
assertNull(configuration.getConfig(null, null, 200));
}
@Test
void testGetInternalProperty() {
assertNull(configuration.getInternalProperty(null));
}
@Test
void testGetProperties() {
assertNull(configuration.getProperties(null, null));
assertNull(configuration.getProperties(null, null, 100L));
}
@Test
void testAddListener() {
configuration.addListener(null, null);
configuration.addListener(null, null, null);
}
@Test
void testRemoveListener() {
configuration.removeListener(null, null);
configuration.removeListener(null, null, null);
}
@Test
void testClose() throws Exception {
configuration.close();
}
/**
* Test {@link AbstractDynamicConfiguration#getGroup()} and
* {@link AbstractDynamicConfiguration#getDefaultGroup()} methods
*
* @since 2.7.8
*/
@Test
void testGetGroupAndGetDefaultGroup() {
assertEquals(configuration.getGroup(), configuration.getDefaultGroup());
assertEquals(DEFAULT_GROUP, configuration.getDefaultGroup());
}
/**
* Test {@link AbstractDynamicConfiguration#getTimeout()} and
* {@link AbstractDynamicConfiguration#getDefaultTimeout()} methods
*
* @since 2.7.8
*/
@Test
void testGetTimeoutAndGetDefaultTimeout() {
assertEquals(configuration.getTimeout(), configuration.getDefaultTimeout());
assertEquals(-1L, configuration.getDefaultTimeout());
}
/**
* Test {@link AbstractDynamicConfiguration#removeConfig(String, String)} and
* {@link AbstractDynamicConfiguration#doRemoveConfig(String, String)} methods
*
* @since 2.7.8
*/
@Test
void testRemoveConfigAndDoRemoveConfig() throws Exception {
String key = null;
String group = null;
assertEquals(configuration.removeConfig(key, group), configuration.doRemoveConfig(key, group));
assertFalse(configuration.removeConfig(key, group));
}
}
| 6,433 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter.file;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.URL.valueOf;
import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP;
import static org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration.CONFIG_CENTER_DIR_PARAM_NAME;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link FileSystemDynamicConfiguration} Test
*/
// Test often failed on GitHub Actions Platform because of file system on Azure
// Change to Disabled because DisabledIfEnvironmentVariable does not work on GitHub.
@Disabled
class FileSystemDynamicConfigurationTest {
private final Logger logger = LoggerFactory.getLogger(getClass());
private FileSystemDynamicConfiguration configuration;
private static final String KEY = "abc-def-ghi";
private static final String CONTENT = "Hello,World";
@BeforeEach
public void init() {
File rootDirectory = new File(getClassPath(), "config-center");
rootDirectory.mkdirs();
try {
FileUtils.cleanDirectory(rootDirectory);
} catch (IOException e) {
e.printStackTrace();
}
URL url = valueOf("dubbo://127.0.0.1:20880")
.addParameter(CONFIG_CENTER_DIR_PARAM_NAME, rootDirectory.getAbsolutePath());
configuration = new FileSystemDynamicConfiguration(url);
}
@AfterEach
public void destroy() throws Exception {
FileUtils.deleteQuietly(configuration.getRootDirectory());
configuration.close();
}
private String getClassPath() {
return getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
}
@Test
void testInit() {
assertEquals(new File(getClassPath(), "config-center"), configuration.getRootDirectory());
assertEquals("UTF-8", configuration.getEncoding());
assertEquals(
ThreadPoolExecutor.class, configuration.getWorkersThreadPool().getClass());
assertEquals(1, (configuration.getWorkersThreadPool()).getCorePoolSize());
assertEquals(1, (configuration.getWorkersThreadPool()).getMaximumPoolSize());
if (configuration.isBasedPoolingWatchService()) {
assertEquals(2, configuration.getDelay());
} else {
assertNull(configuration.getDelay());
}
}
@Test
void testPublishAndGetConfig() {
assertTrue(configuration.publishConfig(KEY, CONTENT));
assertTrue(configuration.publishConfig(KEY, CONTENT));
assertTrue(configuration.publishConfig(KEY, CONTENT));
assertEquals(CONTENT, configuration.getConfig(KEY, DEFAULT_GROUP));
}
@Test
void testAddAndRemoveListener() throws InterruptedException {
configuration.publishConfig(KEY, "A");
AtomicBoolean processedEvent = new AtomicBoolean();
configuration.addListener(KEY, event -> {
processedEvent.set(true);
assertEquals(KEY, event.getKey());
logger.info(
String.format("[%s] " + event + "\n", Thread.currentThread().getName()));
});
configuration.publishConfig(KEY, "B");
while (!processedEvent.get()) {
Thread.sleep(1 * 1000L);
}
processedEvent.set(false);
configuration.publishConfig(KEY, "C");
while (!processedEvent.get()) {
Thread.sleep(1 * 1000L);
}
processedEvent.set(false);
configuration.publishConfig(KEY, "D");
while (!processedEvent.get()) {
Thread.sleep(1 * 1000L);
}
configuration.addListener("test", "test", event -> {
processedEvent.set(true);
assertEquals("test", event.getKey());
logger.info(
String.format("[%s] " + event + "\n", Thread.currentThread().getName()));
});
processedEvent.set(false);
configuration.publishConfig("test", "test", "TEST");
while (!processedEvent.get()) {
Thread.sleep(1 * 1000L);
}
configuration.publishConfig("test", "test", "TEST");
configuration.publishConfig("test", "test", "TEST");
configuration.publishConfig("test", "test", "TEST");
processedEvent.set(false);
configuration.getRootDirectory();
File keyFile = new File(KEY, DEFAULT_GROUP);
FileUtils.deleteQuietly(keyFile);
while (!processedEvent.get()) {
Thread.sleep(1 * 1000L);
}
}
@Test
void testRemoveConfig() throws Exception {
assertTrue(configuration.publishConfig(KEY, DEFAULT_GROUP, "A"));
assertEquals(
"A",
FileUtils.readFileToString(configuration.configFile(KEY, DEFAULT_GROUP), configuration.getEncoding()));
assertTrue(configuration.removeConfig(KEY, DEFAULT_GROUP));
assertFalse(configuration.configFile(KEY, DEFAULT_GROUP).exists());
}
//
// @Test
// public void testGetConfigKeys() throws Exception {
//
// assertTrue(configuration.publishConfig("A", DEFAULT_GROUP, "A"));
//
// assertTrue(configuration.publishConfig("B", DEFAULT_GROUP, "B"));
//
// assertTrue(configuration.publishConfig("C", DEFAULT_GROUP, "C"));
//
// assertEquals(new TreeSet(asList("A", "B", "C")), configuration.getConfigKeys(DEFAULT_GROUP));
// }
}
| 6,434 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter.file;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link FileSystemDynamicConfigurationFactory} Test
*
* @since 2.7.5
*/
class FileSystemDynamicConfigurationFactoryTest {
@Test
void testGetFactory() {
assertEquals(
FileSystemDynamicConfigurationFactory.class,
ConfigurationUtils.getDynamicConfigurationFactory(ApplicationModel.defaultModel(), "file")
.getClass());
}
}
| 6,435 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
import org.apache.dubbo.rpc.model.person.BigPerson;
import org.apache.dubbo.rpc.model.person.FullAddress;
import org.apache.dubbo.rpc.model.person.PersonInfo;
import org.apache.dubbo.rpc.model.person.PersonStatus;
import org.apache.dubbo.rpc.model.person.Phone;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JavaBeanSerializeUtilTest {
@Test
void testSerialize_Primitive() {
JavaBeanDescriptor descriptor;
descriptor = JavaBeanSerializeUtil.serialize(Integer.MAX_VALUE);
Assertions.assertTrue(descriptor.isPrimitiveType());
Assertions.assertEquals(Integer.MAX_VALUE, descriptor.getPrimitiveProperty());
Date now = new Date();
descriptor = JavaBeanSerializeUtil.serialize(now);
Assertions.assertTrue(descriptor.isPrimitiveType());
Assertions.assertEquals(now, descriptor.getPrimitiveProperty());
}
@Test
void testSerialize_Primitive_NUll() {
JavaBeanDescriptor descriptor;
descriptor = JavaBeanSerializeUtil.serialize(null);
Assertions.assertNull(descriptor);
}
@Test
void testDeserialize_Primitive() {
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.setPrimitiveProperty(Long.MAX_VALUE);
Assertions.assertEquals(Long.MAX_VALUE, JavaBeanSerializeUtil.deserialize(descriptor));
BigDecimal decimal = BigDecimal.TEN;
Assertions.assertEquals(Long.MAX_VALUE, descriptor.setPrimitiveProperty(decimal));
Assertions.assertEquals(decimal, JavaBeanSerializeUtil.deserialize(descriptor));
String string = UUID.randomUUID().toString();
Assertions.assertEquals(decimal, descriptor.setPrimitiveProperty(string));
Assertions.assertEquals(string, JavaBeanSerializeUtil.deserialize(descriptor));
}
@Test
void testDeserialize_Primitive0() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN + 1);
});
}
@Test
void testDeserialize_Null() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(null, JavaBeanDescriptor.TYPE_BEAN);
});
}
@Test
void testDeserialize_containsProperty() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.containsProperty(null);
});
}
@Test
void testSetEnumNameProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName());
});
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_ENUM);
String oldValueOrigin = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName());
Assertions.assertNull(oldValueOrigin);
String oldValueNext = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName());
Assertions.assertEquals(oldValueNext, descriptor.getEnumPropertyName());
}
@Test
void testGetEnumNameProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.getEnumPropertyName();
});
}
@Test
void testSetClassNameProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName());
});
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_CLASS);
String oldValue1 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName());
Assertions.assertNull(oldValue1);
String oldValue2 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName());
Assertions.assertEquals(oldValue2, descriptor.getClassNameProperty());
}
@Test
void testGetClassNameProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.getClassNameProperty();
});
}
@Test
void testSetPrimitiveProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN);
descriptor.setPrimitiveProperty(JavaBeanDescriptor.class.getName());
});
}
@Test
void testGetPrimitiveProperty() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavaBeanDescriptor descriptor =
new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN);
descriptor.getPrimitiveProperty();
});
}
@Test
void testDeserialize_get_and_set() {
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN);
descriptor.setType(JavaBeanDescriptor.TYPE_PRIMITIVE);
Assertions.assertEquals(descriptor.getType(), JavaBeanDescriptor.TYPE_PRIMITIVE);
descriptor.setClassName(JavaBeanDescriptor.class.getName());
Assertions.assertEquals(JavaBeanDescriptor.class.getName(), descriptor.getClassName());
}
@Test
void testSerialize_Array() {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(array, JavaBeanAccessor.METHOD);
Assertions.assertTrue(descriptor.isArrayType());
Assertions.assertEquals(int.class.getName(), descriptor.getClassName());
for (int i = 0; i < array.length; i++) {
Assertions.assertEquals(array[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty());
}
Integer[] integers = new Integer[] {1, 2, 3, 4, null, null, null};
descriptor = JavaBeanSerializeUtil.serialize(integers, JavaBeanAccessor.METHOD);
Assertions.assertTrue(descriptor.isArrayType());
Assertions.assertEquals(Integer.class.getName(), descriptor.getClassName());
Assertions.assertEquals(integers.length, descriptor.propertySize());
for (int i = 0; i < integers.length; i++) {
if (integers[i] == null) {
Assertions.assertSame(integers[i], descriptor.getProperty(i));
} else {
Assertions.assertEquals(
integers[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty());
}
}
int[][] second = {{1, 2}, {3, 4}};
descriptor = JavaBeanSerializeUtil.serialize(second, JavaBeanAccessor.METHOD);
Assertions.assertTrue(descriptor.isArrayType());
Assertions.assertEquals(int[].class.getName(), descriptor.getClassName());
for (int i = 0; i < second.length; i++) {
for (int j = 0; j < second[i].length; j++) {
JavaBeanDescriptor item = (((JavaBeanDescriptor) descriptor.getProperty(i)));
Assertions.assertTrue(item.isArrayType());
Assertions.assertEquals(int.class.getName(), item.getClassName());
Assertions.assertEquals(
second[i][j], ((JavaBeanDescriptor) item.getProperty(j)).getPrimitiveProperty());
}
}
BigPerson[] persons = new BigPerson[] {createBigPerson(), createBigPerson()};
descriptor = JavaBeanSerializeUtil.serialize(persons);
Assertions.assertTrue(descriptor.isArrayType());
Assertions.assertEquals(BigPerson.class.getName(), descriptor.getClassName());
for (int i = 0; i < persons.length; i++) {
assertEqualsBigPerson(persons[i], descriptor.getProperty(i));
}
}
@Test
void testConstructorArg() {
Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(boolean.class));
Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(Boolean.class));
Assertions.assertEquals((byte) 0, JavaBeanSerializeUtil.getConstructorArg(byte.class));
Assertions.assertEquals((byte) 0, JavaBeanSerializeUtil.getConstructorArg(Byte.class));
Assertions.assertEquals((short) 0, JavaBeanSerializeUtil.getConstructorArg(short.class));
Assertions.assertEquals((short) 0, JavaBeanSerializeUtil.getConstructorArg(Short.class));
Assertions.assertEquals(0, JavaBeanSerializeUtil.getConstructorArg(int.class));
Assertions.assertEquals(0, JavaBeanSerializeUtil.getConstructorArg(Integer.class));
Assertions.assertEquals((long) 0, JavaBeanSerializeUtil.getConstructorArg(long.class));
Assertions.assertEquals((long) 0, JavaBeanSerializeUtil.getConstructorArg(Long.class));
Assertions.assertEquals((float) 0, JavaBeanSerializeUtil.getConstructorArg(float.class));
Assertions.assertEquals((float) 0, JavaBeanSerializeUtil.getConstructorArg(Float.class));
Assertions.assertEquals((double) 0, JavaBeanSerializeUtil.getConstructorArg(double.class));
Assertions.assertEquals((double) 0, JavaBeanSerializeUtil.getConstructorArg(Double.class));
Assertions.assertEquals((char) 0, JavaBeanSerializeUtil.getConstructorArg(char.class));
Assertions.assertEquals(new Character((char) 0), JavaBeanSerializeUtil.getConstructorArg(Character.class));
Assertions.assertNull(JavaBeanSerializeUtil.getConstructorArg(JavaBeanSerializeUtil.class));
}
@Test
void testDeserialize_Array() {
final int len = 10;
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY);
for (int i = 0; i < len; i++) {
descriptor.setProperty(i, i);
}
Object obj = JavaBeanSerializeUtil.deserialize(descriptor);
Assertions.assertTrue(obj.getClass().isArray());
Assertions.assertSame(int.class, obj.getClass().getComponentType());
for (int i = 0; i < len; i++) {
Assertions.assertEquals(i, Array.get(obj, i));
}
descriptor = new JavaBeanDescriptor(int[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY);
for (int i = 0; i < len; i++) {
JavaBeanDescriptor innerItem = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY);
for (int j = 0; j < len; j++) {
innerItem.setProperty(j, j);
}
descriptor.setProperty(i, innerItem);
}
obj = JavaBeanSerializeUtil.deserialize(descriptor);
Assertions.assertTrue(obj.getClass().isArray());
Assertions.assertEquals(int[].class, obj.getClass().getComponentType());
for (int i = 0; i < len; i++) {
Object innerItem = Array.get(obj, i);
Assertions.assertTrue(innerItem.getClass().isArray());
Assertions.assertEquals(int.class, innerItem.getClass().getComponentType());
for (int j = 0; j < len; j++) {
Assertions.assertEquals(j, Array.get(innerItem, j));
}
}
descriptor = new JavaBeanDescriptor(BigPerson[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY);
JavaBeanDescriptor innerDescriptor =
new JavaBeanDescriptor(BigPerson.class.getName(), JavaBeanDescriptor.TYPE_ARRAY);
innerDescriptor.setProperty(0, JavaBeanSerializeUtil.serialize(createBigPerson(), JavaBeanAccessor.METHOD));
descriptor.setProperty(0, innerDescriptor);
obj = JavaBeanSerializeUtil.deserialize(descriptor);
Assertions.assertTrue(obj.getClass().isArray());
Assertions.assertEquals(BigPerson[].class, obj.getClass().getComponentType());
Assertions.assertEquals(1, Array.getLength(obj));
obj = Array.get(obj, 0);
Assertions.assertTrue(obj.getClass().isArray());
Assertions.assertEquals(BigPerson.class, obj.getClass().getComponentType());
Assertions.assertEquals(1, Array.getLength(obj));
Assertions.assertEquals(createBigPerson(), Array.get(obj, 0));
}
@Test
void test_Circular_Reference() {
Parent parent = new Parent();
parent.setAge(Integer.MAX_VALUE);
parent.setEmail("a@b");
parent.setName("zhangsan");
Child child = new Child();
child.setAge(100);
child.setName("lisi");
child.setParent(parent);
parent.setChild(child);
JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(parent, JavaBeanAccessor.METHOD);
Assertions.assertTrue(descriptor.isBeanType());
assertEqualsPrimitive(parent.getAge(), descriptor.getProperty("age"));
assertEqualsPrimitive(parent.getName(), descriptor.getProperty("name"));
assertEqualsPrimitive(parent.getEmail(), descriptor.getProperty("email"));
JavaBeanDescriptor childDescriptor = (JavaBeanDescriptor) descriptor.getProperty("child");
Assertions.assertSame(descriptor, childDescriptor.getProperty("parent"));
assertEqualsPrimitive(child.getName(), childDescriptor.getProperty("name"));
assertEqualsPrimitive(child.getAge(), childDescriptor.getProperty("age"));
}
public static class Parent {
public String gender;
public String email;
String name;
int age;
Child child;
private String securityEmail;
public static Parent getNewParent() {
return new Parent();
}
public String getEmail() {
return this.securityEmail;
}
public void setEmail(String email) {
this.securityEmail = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
public static class Child {
public String gender;
public int age;
String toy;
Parent parent;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getToy() {
return toy;
}
public void setToy(String toy) {
this.toy = toy;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
@Test
void testBeanSerialize() {
Bean bean = new Bean();
bean.setDate(new Date());
bean.setStatus(PersonStatus.ENABLED);
bean.setType(Bean.class);
bean.setArray(new Phone[] {});
Collection<Phone> collection = new ArrayList<Phone>();
bean.setCollection(collection);
Phone phone = new Phone();
collection.add(phone);
Map<String, FullAddress> map = new HashMap<String, FullAddress>();
FullAddress address = new FullAddress();
map.put("first", address);
bean.setAddresses(map);
JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD);
Assertions.assertTrue(descriptor.isBeanType());
assertEqualsPrimitive(bean.getDate(), descriptor.getProperty("date"));
assertEqualsEnum(bean.getStatus(), descriptor.getProperty("status"));
Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("type")).isClassType());
Assertions.assertEquals(
Bean.class.getName(), ((JavaBeanDescriptor) descriptor.getProperty("type")).getClassNameProperty());
Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("array")).isArrayType());
Assertions.assertEquals(0, ((JavaBeanDescriptor) descriptor.getProperty("array")).propertySize());
JavaBeanDescriptor property = (JavaBeanDescriptor) descriptor.getProperty("collection");
Assertions.assertTrue(property.isCollectionType());
Assertions.assertEquals(1, property.propertySize());
property = (JavaBeanDescriptor) property.getProperty(0);
Assertions.assertTrue(property.isBeanType());
Assertions.assertEquals(Phone.class.getName(), property.getClassName());
Assertions.assertEquals(0, property.propertySize());
property = (JavaBeanDescriptor) descriptor.getProperty("addresses");
Assertions.assertTrue(property.isMapType());
Assertions.assertEquals(bean.getAddresses().getClass().getName(), property.getClassName());
Assertions.assertEquals(1, property.propertySize());
Map.Entry<Object, Object> entry = property.iterator().next();
Assertions.assertTrue(((JavaBeanDescriptor) entry.getKey()).isPrimitiveType());
Assertions.assertEquals("first", ((JavaBeanDescriptor) entry.getKey()).getPrimitiveProperty());
Assertions.assertTrue(((JavaBeanDescriptor) entry.getValue()).isBeanType());
Assertions.assertEquals(FullAddress.class.getName(), ((JavaBeanDescriptor) entry.getValue()).getClassName());
Assertions.assertEquals(0, ((JavaBeanDescriptor) entry.getValue()).propertySize());
}
@Test
void testDeserializeBean() {
Bean bean = new Bean();
bean.setDate(new Date());
bean.setStatus(PersonStatus.ENABLED);
bean.setType(Bean.class);
bean.setArray(new Phone[] {});
Collection<Phone> collection = new ArrayList<Phone>();
bean.setCollection(collection);
Phone phone = new Phone();
collection.add(phone);
Map<String, FullAddress> map = new HashMap<String, FullAddress>();
FullAddress address = new FullAddress();
map.put("first", address);
bean.setAddresses(map);
JavaBeanDescriptor beanDescriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD);
Object deser = JavaBeanSerializeUtil.deserialize(beanDescriptor);
Assertions.assertTrue(deser instanceof Bean);
Bean deserBean = (Bean) deser;
Assertions.assertEquals(bean.getDate(), deserBean.getDate());
Assertions.assertEquals(bean.getStatus(), deserBean.getStatus());
Assertions.assertEquals(bean.getType(), deserBean.getType());
Assertions.assertEquals(
bean.getCollection().size(), deserBean.getCollection().size());
Assertions.assertEquals(
bean.getCollection().iterator().next().getClass(),
deserBean.getCollection().iterator().next().getClass());
Assertions.assertEquals(
bean.getAddresses().size(), deserBean.getAddresses().size());
Assertions.assertEquals(
bean.getAddresses().entrySet().iterator().next().getKey(),
deserBean.getAddresses().entrySet().iterator().next().getKey());
Assertions.assertEquals(
bean.getAddresses().entrySet().iterator().next().getValue().getClass(),
deserBean.getAddresses().entrySet().iterator().next().getValue().getClass());
}
@Test
@SuppressWarnings("unchecked")
public void testSerializeJavaBeanDescriptor() {
JavaBeanDescriptor descriptor = new JavaBeanDescriptor();
JavaBeanDescriptor result = JavaBeanSerializeUtil.serialize(descriptor);
Assertions.assertSame(descriptor, result);
Map map = new HashMap();
map.put("first", descriptor);
result = JavaBeanSerializeUtil.serialize(map);
Assertions.assertTrue(result.isMapType());
Assertions.assertEquals(HashMap.class.getName(), result.getClassName());
Assertions.assertEquals(map.size(), result.propertySize());
Object object = result.iterator().next().getValue();
Assertions.assertTrue(object instanceof JavaBeanDescriptor);
JavaBeanDescriptor actual = (JavaBeanDescriptor) object;
Assertions.assertEquals(map.get("first"), actual);
}
static void assertEqualsEnum(Enum<?> expected, Object obj) {
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj;
Assertions.assertTrue(descriptor.isEnumType());
Assertions.assertEquals(expected.getClass().getName(), descriptor.getClassName());
Assertions.assertEquals(expected.name(), descriptor.getEnumPropertyName());
}
static void assertEqualsPrimitive(Object expected, Object obj) {
if (expected == null) {
return;
}
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj;
Assertions.assertTrue(descriptor.isPrimitiveType());
Assertions.assertEquals(expected, descriptor.getPrimitiveProperty());
}
static void assertEqualsBigPerson(BigPerson person, Object obj) {
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj;
Assertions.assertTrue(descriptor.isBeanType());
assertEqualsPrimitive(person.getPersonId(), descriptor.getProperty("personId"));
assertEqualsPrimitive(person.getLoginName(), descriptor.getProperty("loginName"));
assertEqualsEnum(person.getStatus(), descriptor.getProperty("status"));
assertEqualsPrimitive(person.getEmail(), descriptor.getProperty("email"));
assertEqualsPrimitive(person.getPenName(), descriptor.getProperty("penName"));
JavaBeanDescriptor infoProfile = (JavaBeanDescriptor) descriptor.getProperty("infoProfile");
Assertions.assertTrue(infoProfile.isBeanType());
JavaBeanDescriptor phones = (JavaBeanDescriptor) infoProfile.getProperty("phones");
Assertions.assertTrue(phones.isCollectionType());
assertEqualsPhone(person.getInfoProfile().getPhones().get(0), phones.getProperty(0));
assertEqualsPhone(person.getInfoProfile().getPhones().get(1), phones.getProperty(1));
assertEqualsPhone(person.getInfoProfile().getFax(), infoProfile.getProperty("fax"));
assertEqualsFullAddress(person.getInfoProfile().getFullAddress(), infoProfile.getProperty("fullAddress"));
assertEqualsPrimitive(person.getInfoProfile().getMobileNo(), infoProfile.getProperty("mobileNo"));
assertEqualsPrimitive(person.getInfoProfile().getName(), infoProfile.getProperty("name"));
assertEqualsPrimitive(person.getInfoProfile().getDepartment(), infoProfile.getProperty("department"));
assertEqualsPrimitive(person.getInfoProfile().getJobTitle(), infoProfile.getProperty("jobTitle"));
assertEqualsPrimitive(person.getInfoProfile().getHomepageUrl(), infoProfile.getProperty("homepageUrl"));
assertEqualsPrimitive(person.getInfoProfile().isFemale(), infoProfile.getProperty("female"));
assertEqualsPrimitive(person.getInfoProfile().isMale(), infoProfile.getProperty("male"));
}
static void assertEqualsPhone(Phone expected, Object obj) {
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj;
Assertions.assertTrue(descriptor.isBeanType());
if (expected.getArea() != null) {
assertEqualsPrimitive(expected.getArea(), descriptor.getProperty("area"));
}
if (expected.getCountry() != null) {
assertEqualsPrimitive(expected.getCountry(), descriptor.getProperty("country"));
}
if (expected.getExtensionNumber() != null) {
assertEqualsPrimitive(expected.getExtensionNumber(), descriptor.getProperty("extensionNumber"));
}
if (expected.getNumber() != null) {
assertEqualsPrimitive(expected.getNumber(), descriptor.getProperty("number"));
}
}
static void assertEqualsFullAddress(FullAddress expected, Object obj) {
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj;
Assertions.assertTrue(descriptor.isBeanType());
if (expected.getCityId() != null) {
assertEqualsPrimitive(expected.getCityId(), descriptor.getProperty("cityId"));
}
if (expected.getCityName() != null) {
assertEqualsPrimitive(expected.getCityName(), descriptor.getProperty("cityName"));
}
if (expected.getCountryId() != null) {
assertEqualsPrimitive(expected.getCountryId(), descriptor.getProperty("countryId"));
}
if (expected.getCountryName() != null) {
assertEqualsPrimitive(expected.getCountryName(), descriptor.getProperty("countryName"));
}
if (expected.getProvinceName() != null) {
assertEqualsPrimitive(expected.getProvinceName(), descriptor.getProperty("provinceName"));
}
if (expected.getStreetAddress() != null) {
assertEqualsPrimitive(expected.getStreetAddress(), descriptor.getProperty("streetAddress"));
}
if (expected.getZipCode() != null) {
assertEqualsPrimitive(expected.getZipCode(), descriptor.getProperty("zipCode"));
}
}
static BigPerson createBigPerson() {
BigPerson bigPerson;
bigPerson = new BigPerson();
bigPerson.setPersonId("superman111");
bigPerson.setLoginName("superman");
bigPerson.setStatus(PersonStatus.ENABLED);
bigPerson.setEmail("sm@1.com");
bigPerson.setPenName("pname");
ArrayList<Phone> phones = new ArrayList<Phone>();
Phone phone1 = new Phone("86", "0571", "87654321", "001");
Phone phone2 = new Phone("86", "0571", "87654322", "002");
phones.add(phone1);
phones.add(phone2);
PersonInfo pi = new PersonInfo();
pi.setPhones(phones);
Phone fax = new Phone("86", "0571", "87654321", null);
pi.setFax(fax);
FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000");
pi.setFullAddress(addr);
pi.setMobileNo("13584652131");
pi.setMale(true);
pi.setDepartment("b2b");
pi.setHomepageUrl("www.capcom.com");
pi.setJobTitle("qa");
pi.setName("superman");
bigPerson.setInfoProfile(pi);
return bigPerson;
}
}
| 6,436 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JavaBeanAccessorTest {
@Test
void testIsAccessByMethod() {
Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.METHOD));
Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.ALL));
Assertions.assertFalse(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.FIELD));
}
@Test
void testIsAccessByField() {
Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.FIELD));
Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.ALL));
Assertions.assertFalse(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.METHOD));
}
}
| 6,437 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.beanutil;
import org.apache.dubbo.rpc.model.person.FullAddress;
import org.apache.dubbo.rpc.model.person.PersonStatus;
import org.apache.dubbo.rpc.model.person.Phone;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
public class Bean implements Serializable {
private Class<?> type;
private PersonStatus status;
private Date date;
private Phone[] array;
private Collection<Phone> collection;
private Map<String, FullAddress> addresses;
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public PersonStatus getStatus() {
return status;
}
public void setStatus(PersonStatus status) {
this.status = status;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Phone[] getArray() {
return array;
}
public void setArray(Phone[] array) {
this.array = array;
}
public Collection<Phone> getCollection() {
return collection;
}
public void setCollection(Collection<Phone> collection) {
this.collection = collection;
}
public Map<String, FullAddress> getAddresses() {
return addresses;
}
public void setAddresses(Map<String, FullAddress> addresses) {
this.addresses = addresses;
}
}
| 6,438 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.constants;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link CommonConstants} Test-Cases
*
* @since 2.7.8
*/
class CommonConstantsTest {
@Test
void test() {
assertEquals(',', COMMA_SEPARATOR_CHAR);
assertEquals("composite", COMPOSITE_METADATA_STORAGE_TYPE);
assertEquals("service-name-mapping.properties-path", SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY);
assertEquals("META-INF/dubbo/service-name-mapping.properties", DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH);
}
}
| 6,439 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadlocal;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class NamedInternalThreadFactoryTest {
@Test
void newThread() throws Exception {
NamedInternalThreadFactory namedInternalThreadFactory = new NamedInternalThreadFactory();
Thread t = namedInternalThreadFactory.newThread(() -> {});
Assertions.assertEquals(t.getClass(), InternalThread.class, "thread is not InternalThread");
}
}
| 6,440 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadlocal;
import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InternalThreadLocalTest {
private static final int THREADS = 10;
private static final int PERFORMANCE_THREAD_COUNT = 1000;
private static final int GET_COUNT = 1000000;
@AfterEach
public void setup() {
InternalThreadLocalMap.remove();
}
@Test
void testInternalThreadLocal() {
final AtomicInteger index = new AtomicInteger(0);
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
Integer v = index.getAndIncrement();
System.out.println("thread : " + Thread.currentThread().getName() + " init value : " + v);
return v;
}
};
for (int i = 0; i < THREADS; i++) {
Thread t = new Thread(internalThreadLocal::get);
t.start();
}
await().until(index::get, is(THREADS));
}
@Test
void testRemoveAll() {
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
internalThreadLocal.set(1);
Assertions.assertEquals(1, (int) internalThreadLocal.get(), "set failed");
final InternalThreadLocal<String> internalThreadLocalString = new InternalThreadLocal<String>();
internalThreadLocalString.set("value");
Assertions.assertEquals("value", internalThreadLocalString.get(), "set failed");
InternalThreadLocal.removeAll();
Assertions.assertNull(internalThreadLocal.get(), "removeAll failed!");
Assertions.assertNull(internalThreadLocalString.get(), "removeAll failed!");
}
@Test
void testSize() {
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
internalThreadLocal.set(1);
Assertions.assertEquals(1, InternalThreadLocal.size(), "size method is wrong!");
final InternalThreadLocal<String> internalThreadLocalString = new InternalThreadLocal<String>();
internalThreadLocalString.set("value");
Assertions.assertEquals(2, InternalThreadLocal.size(), "size method is wrong!");
InternalThreadLocal.removeAll();
}
@Test
void testSetAndGet() {
final Integer testVal = 10;
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
internalThreadLocal.set(testVal);
Assertions.assertEquals(testVal, internalThreadLocal.get(), "set is not equals get");
}
@Test
void testRemove() {
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
internalThreadLocal.set(1);
Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!");
internalThreadLocal.remove();
Assertions.assertNull(internalThreadLocal.get(), "remove failed!");
}
@Test
void testOnRemove() {
final Integer[] valueToRemove = {null};
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>() {
@Override
protected void onRemoval(Integer value) {
// value calculate
valueToRemove[0] = value + 1;
}
};
internalThreadLocal.set(1);
Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!");
internalThreadLocal.remove();
Assertions.assertEquals(2, (int) valueToRemove[0], "onRemove method failed!");
}
@Test
void testMultiThreadSetAndGet() throws InterruptedException {
final Integer testVal1 = 10;
final Integer testVal2 = 20;
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
final CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
internalThreadLocal.set(testVal1);
Assertions.assertEquals(testVal1, internalThreadLocal.get(), "set is not equals get");
countDownLatch.countDown();
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
internalThreadLocal.set(testVal2);
Assertions.assertEquals(testVal2, internalThreadLocal.get(), "set is not equals get");
countDownLatch.countDown();
}
});
t2.start();
countDownLatch.await();
}
/**
* print
* take[2689]ms
* <p></p>
* This test is based on a Machine with 4 core and 16g memory.
*/
@Test
void testPerformanceTradition() {
final ThreadLocal<String>[] caches1 = new ThreadLocal[PERFORMANCE_THREAD_COUNT];
final Thread mainThread = Thread.currentThread();
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
caches1[i] = new ThreadLocal<String>();
}
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
caches1[i].set("float.lu");
}
long start = System.nanoTime();
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
for (int j = 0; j < GET_COUNT; j++) {
caches1[i].get();
}
}
long end = System.nanoTime();
System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + "]ms");
LockSupport.unpark(mainThread);
}
});
t1.start();
LockSupport.park(mainThread);
}
/**
* print
* take[14]ms
* <p></p>
* This test is based on a Machine with 4 core and 16g memory.
*/
@Test
void testPerformance() {
final InternalThreadLocal<String>[] caches = new InternalThreadLocal[PERFORMANCE_THREAD_COUNT];
final Thread mainThread = Thread.currentThread();
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
caches[i] = new InternalThreadLocal<String>();
}
Thread t = new InternalThread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
caches[i].set("float.lu");
}
long start = System.nanoTime();
for (int i = 0; i < PERFORMANCE_THREAD_COUNT; i++) {
for (int j = 0; j < GET_COUNT; j++) {
caches[i].get();
}
}
long end = System.nanoTime();
System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + "]ms");
LockSupport.unpark(mainThread);
}
});
t.start();
LockSupport.park(mainThread);
}
@Test
void testConstructionWithIndex() throws Exception {
// reset ARRAY_LIST_CAPACITY_MAX_SIZE to speed up
int NEW_ARRAY_LIST_CAPACITY_MAX_SIZE = 8;
Field nextIndexField = InternalThreadLocalMap.class.getDeclaredField("NEXT_INDEX");
nextIndexField.setAccessible(true);
AtomicInteger nextIndex = (AtomicInteger) nextIndexField.get(AtomicInteger.class);
int arrayListCapacityMaxSize = InternalThreadLocalMap.ARRAY_LIST_CAPACITY_MAX_SIZE;
int nextIndex_before = nextIndex.incrementAndGet();
nextIndex.set(0);
final AtomicReference<Throwable> throwable = new AtomicReference<Throwable>();
try {
InternalThreadLocalMap.ARRAY_LIST_CAPACITY_MAX_SIZE = NEW_ARRAY_LIST_CAPACITY_MAX_SIZE;
while (nextIndex.get() < NEW_ARRAY_LIST_CAPACITY_MAX_SIZE) {
new InternalThreadLocal<Boolean>();
}
assertEquals(NEW_ARRAY_LIST_CAPACITY_MAX_SIZE - 1, InternalThreadLocalMap.lastVariableIndex());
try {
new InternalThreadLocal<Boolean>();
} catch (Throwable t) {
throwable.set(t);
}
// Assert the max index cannot greater than (ARRAY_LIST_CAPACITY_MAX_SIZE - 1)
assertThat(throwable.get(), is(instanceOf(IllegalStateException.class)));
// Assert the index was reset to ARRAY_LIST_CAPACITY_MAX_SIZE after it reaches ARRAY_LIST_CAPACITY_MAX_SIZE
assertEquals(NEW_ARRAY_LIST_CAPACITY_MAX_SIZE - 1, InternalThreadLocalMap.lastVariableIndex());
} finally {
// Restore the index
nextIndex.set(nextIndex_before);
InternalThreadLocalMap.ARRAY_LIST_CAPACITY_MAX_SIZE = arrayListCapacityMaxSize;
}
}
@Test
void testInternalThreadLocalMapExpand() throws Exception {
final AtomicReference<Throwable> throwable = new AtomicReference<Throwable>();
Runnable runnable = new Runnable() {
@Override
public void run() {
int expand_threshold = 1 << 30;
try {
InternalThreadLocalMap.get().setIndexedVariable(expand_threshold, null);
} catch (Throwable t) {
throwable.set(t);
}
}
};
InternalThread internalThread = new InternalThread(runnable);
internalThread.start();
internalThread.join();
// Assert the expanded size is not overflowed to negative value
assertThat(throwable.get(), is(not(instanceOf(NegativeArraySizeException.class))));
}
}
| 6,441 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.timer;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class HashedWheelTimerTest {
private CountDownLatch tryStopTaskCountDownLatch = new CountDownLatch(1);
private CountDownLatch errorTaskCountDownLatch = new CountDownLatch(1);
private static class EmptyTask implements TimerTask {
@Override
public void run(Timeout timeout) {}
}
private static class BlockTask implements TimerTask {
@Override
public void run(Timeout timeout) throws InterruptedException {
this.wait();
}
}
private class ErrorTask implements TimerTask {
@Override
public void run(Timeout timeout) {
errorTaskCountDownLatch.countDown();
throw new RuntimeException("Test");
}
}
private class TryStopTask implements TimerTask {
private Timer timer;
public TryStopTask(Timer timer) {
this.timer = timer;
}
@Override
public void run(Timeout timeout) {
Assertions.assertThrows(RuntimeException.class, () -> timer.stop());
tryStopTaskCountDownLatch.countDown();
}
}
@Test
void constructorTest() {
// use weak reference to let gc work every time
// which can check finalize method and reduce memory usage in time
WeakReference<Timer> timer = new WeakReference<>(new HashedWheelTimer());
timer = new WeakReference<>(new HashedWheelTimer(100, TimeUnit.MILLISECONDS));
timer = new WeakReference<>(new HashedWheelTimer(100, TimeUnit.MILLISECONDS, 8));
// to cover arg check branches
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(null, 100, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 0, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 100, null, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), 100, TimeUnit.MILLISECONDS, 0, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), Long.MAX_VALUE, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true),
100,
TimeUnit.MILLISECONDS,
Integer.MAX_VALUE,
-1);
});
for (int i = 0; i < 128; i++) {
// to trigger INSTANCE_COUNT_LIMIT
timer = new WeakReference<>(new HashedWheelTimer());
}
System.gc();
}
@Test
void createTaskTest() throws InterruptedException {
HashedWheelTimer timer = new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), 10, TimeUnit.MILLISECONDS, 8, 8);
EmptyTask emptyTask = new EmptyTask();
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(null, 5, TimeUnit.SECONDS));
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(emptyTask, 5, null));
Timeout timeout = timer.newTimeout(new ErrorTask(), 10, TimeUnit.MILLISECONDS);
errorTaskCountDownLatch.await();
Assertions.assertFalse(timeout.cancel());
Assertions.assertFalse(timeout.isCancelled());
Assertions.assertNotNull(timeout.toString());
Assertions.assertEquals(timeout.timer(), timer);
timeout = timer.newTimeout(emptyTask, 1000, TimeUnit.SECONDS);
timeout.cancel();
Assertions.assertTrue(timeout.isCancelled());
List<Timeout> timeouts = new LinkedList<>();
BlockTask blockTask = new BlockTask();
while (timer.pendingTimeouts() < 8) {
// to trigger maxPendingTimeouts
timeout = timer.newTimeout(blockTask, -1, TimeUnit.MILLISECONDS);
timeouts.add(timeout);
Assertions.assertNotNull(timeout.toString());
}
Assertions.assertEquals(8, timer.pendingTimeouts());
// this will throw an exception because of maxPendingTimeouts
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(blockTask, 1, TimeUnit.MILLISECONDS));
Timeout secondTimeout = timeouts.get(2);
// wait until the task expired
await().until(secondTimeout::isExpired);
timer.stop();
}
@Test
void stopTaskTest() throws InterruptedException {
Timer timer = new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true));
timer.newTimeout(new TryStopTask(timer), 10, TimeUnit.MILLISECONDS);
tryStopTaskCountDownLatch.await();
for (int i = 0; i < 8; i++) {
timer.newTimeout(new EmptyTask(), 0, TimeUnit.SECONDS);
}
// stop timer
timer.stop();
Assertions.assertTrue(timer.isStop());
// this will throw an exception
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(new EmptyTask(), 5, TimeUnit.SECONDS));
}
}
| 6,442 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.File;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class BytesTest {
private final byte[] b1 =
"adpfioha;eoh;aldfadl;kfadslkfdajfio123431241235123davas;odvwe;lmzcoqpwoewqogineopwqihwqetup\n\tejqf;lajsfd中文字符0da0gsaofdsf==adfasdfs"
.getBytes();
private final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64.
private byte[] bytes1 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67, 23};
private byte[] bytes2 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67};
@Test
void testMain() {
short s = (short) 0xabcd;
assertThat(s, is(Bytes.bytes2short(Bytes.short2bytes(s))));
int i = 198284;
assertThat(i, is(Bytes.bytes2int(Bytes.int2bytes(i))));
long l = 13841747174L;
assertThat(l, is(Bytes.bytes2long(Bytes.long2bytes(l))));
float f = 1.3f;
assertThat(f, is(Bytes.bytes2float(Bytes.float2bytes(f))));
double d = 11213.3;
assertThat(d, is(Bytes.bytes2double(Bytes.double2bytes(d))));
assertThat(Bytes.int2bytes(i), is(int2bytes(i)));
assertThat(Bytes.long2bytes(l), is(long2bytes(l)));
String str = Bytes.bytes2base64("dubbo".getBytes());
byte[] bytes = Bytes.base642bytes(str, 0, str.length());
assertThat(bytes, is("dubbo".getBytes()));
byte[] bytesWithC64 = Bytes.base642bytes(str, C64);
assertThat(bytesWithC64, is(bytes));
byte[] emptyBytes = Bytes.base642bytes("dubbo", 0, 0);
assertThat(emptyBytes, is("".getBytes()));
assertThat(Bytes.base642bytes("dubbo", 0, 0, ""), is("".getBytes()));
assertThat(Bytes.base642bytes("dubbo", 0, 0, new char[0]), is("".getBytes()));
}
@Test
void testWrongBase64Code() {
Assertions.assertThrows(
IllegalArgumentException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 1, new char[] {'a'}));
}
@Test
void testWrongOffSet() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), -1, 1));
}
@Test
void testLargeLength() {
Assertions.assertThrows(
IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 100000));
}
@Test
void testSmallLength() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, -1));
}
@Test
void testBase64S2b2sFailCaseLog() {
String s1 = Bytes.bytes2base64(bytes1);
byte[] out1 = Bytes.base642bytes(s1);
assertThat(bytes1, is(out1));
String s2 = Bytes.bytes2base64(bytes2);
byte[] out2 = Bytes.base642bytes(s2);
assertThat(bytes2, is(out2));
}
@Test
void testBase642bCharArrCall() {
byte[] stringCall = Bytes.base642bytes("ZHViYm8=", C64);
byte[] charArrCall = Bytes.base642bytes("ZHViYm8=", C64.toCharArray());
assertThat(stringCall, is(charArrCall));
}
@Test
void testHex() {
String str = Bytes.bytes2hex(b1);
assertThat(b1, is(Bytes.hex2bytes(str)));
}
@Test
void testMD5ForString() {
byte[] md5 = Bytes.getMD5("dubbo");
assertThat(md5, is(Bytes.base642bytes("qk4bjCzJ3u2W/gEu8uB1Kg==")));
}
@Test
void testMD5ForFile() throws IOException {
byte[] md5 = Bytes.getMD5(new File(
getClass().getClassLoader().getResource("md5.testfile.txt").getFile()));
assertThat(md5, is(Bytes.base642bytes("iNZ+5qHafVNPLJxHwLKJ3w==")));
}
@Test
void testZip() throws IOException {
String s = "hello world";
byte[] zip = Bytes.zip(s.getBytes());
byte[] unzip = Bytes.unzip(zip);
assertThat(unzip, is(s.getBytes()));
}
@Test
void testBytes2HexWithWrongOffset() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2hex("hello".getBytes(), -1, 1));
}
@Test
void testBytes2HexWithWrongLength() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2hex("hello".getBytes(), 0, 6));
}
private byte[] int2bytes(int x) {
byte[] bb = new byte[4];
bb[0] = (byte) (x >> 24);
bb[1] = (byte) (x >> 16);
bb[2] = (byte) (x >> 8);
bb[3] = (byte) (x >> 0);
return bb;
}
private byte[] long2bytes(long x) {
byte[] bb = new byte[8];
bb[0] = (byte) (x >> 56);
bb[1] = (byte) (x >> 48);
bb[2] = (byte) (x >> 40);
bb[3] = (byte) (x >> 32);
bb[4] = (byte) (x >> 24);
bb[5] = (byte) (x >> 16);
bb[6] = (byte) (x >> 8);
bb[7] = (byte) (x >> 0);
return bb;
}
}
| 6,443 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class UnsafeStringReaderTest {
@Test
void testRead() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
assertThat(reader.markSupported(), is(true));
assertThat(reader.read(), is((int) 'a'));
assertThat(reader.read(), is((int) 'b'));
assertThat(reader.read(), is((int) 'c'));
assertThat(reader.read(), is(-1));
reader.reset();
reader.mark(0);
assertThat(reader.read(), is((int) 'a'));
char[] chars = new char[2];
reader.read(chars);
reader.close();
assertThat(chars[0], is('b'));
assertThat(chars[1], is('c'));
}
@Test
void testSkip() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
assertThat(reader.ready(), is(true));
reader.skip(1);
assertThat(reader.read(), is((int) 'b'));
}
@Test
void testSkipTooLong() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
reader.skip(10);
long skip = reader.skip(10);
assertThat(skip, is(0L));
}
@Test
void testWrongLength() throws IOException {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeStringReader reader = new UnsafeStringReader("abc");
char[] chars = new char[1];
reader.read(chars, 0, 2);
});
}
}
| 6,444 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
class StreamUtilsTest {
@Test
void testMarkSupportedInputStream() throws Exception {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
assertEquals(10, is.available());
is = new PushbackInputStream(is);
assertEquals(10, is.available());
assertFalse(is.markSupported());
is = StreamUtils.markSupportedInputStream(is);
assertEquals(10, is.available());
is.mark(0);
assertEquals((int) '0', is.read());
assertEquals((int) '1', is.read());
is.reset();
assertEquals((int) '0', is.read());
assertEquals((int) '1', is.read());
assertEquals((int) '2', is.read());
is.mark(0);
assertEquals((int) '3', is.read());
assertEquals((int) '4', is.read());
assertEquals((int) '5', is.read());
is.reset();
assertEquals((int) '3', is.read());
assertEquals((int) '4', is.read());
is.mark(0);
assertEquals((int) '5', is.read());
assertEquals((int) '6', is.read());
is.reset();
assertEquals((int) '5', is.read());
assertEquals((int) '6', is.read());
assertEquals((int) '7', is.read());
assertEquals((int) '8', is.read());
assertEquals((int) '9', is.read());
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.mark(0);
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.reset();
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.close();
}
@Test
void testLimitedInputStream() throws Exception {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
assertThat(10, is(is.available()));
is = StreamUtils.limitedInputStream(is, 2);
assertThat(2, is(is.available()));
assertThat(is.markSupported(), is(true));
is.mark(0);
assertEquals((int) '0', is.read());
assertEquals((int) '1', is.read());
assertEquals(-1, is.read());
is.reset();
is.skip(1);
assertEquals((int) '1', is.read());
is.reset();
is.skip(-1);
assertEquals((int) '0', is.read());
is.reset();
byte[] bytes = new byte[2];
int read = is.read(bytes, 1, 1);
assertThat(read, is(1));
is.reset();
StreamUtils.skipUnusedStream(is);
assertEquals(-1, is.read());
is.close();
}
@Test
void testMarkInputSupport() {
Assertions.assertThrows(IOException.class, () -> {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
try {
is = StreamUtils.markSupportedInputStream(new PushbackInputStream(is), 1);
is.mark(1);
int read = is.read();
assertThat(read, is((int) '0'));
is.skip(1);
is.read();
} finally {
if (is != null) {
is.close();
}
}
});
}
@Test
void testSkipForOriginMarkSupportInput() throws IOException {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
InputStream newIs = StreamUtils.markSupportedInputStream(is, 1);
assertThat(newIs, is(is));
is.close();
}
@Test
void testReadEmptyByteArray() {
Assertions.assertThrows(NullPointerException.class, () -> {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
try {
is = StreamUtils.limitedInputStream(is, 2);
is.read(null, 0, 1);
} finally {
if (is != null) {
is.close();
}
}
});
}
@Test
void testReadWithWrongOffset() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
try {
is = StreamUtils.limitedInputStream(is, 2);
is.read(new byte[1], -1, 1);
} finally {
if (is != null) {
is.close();
}
}
});
}
}
| 6,445 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class UnsafeStringWriterTest {
@Test
void testWrite() {
UnsafeStringWriter writer = new UnsafeStringWriter();
writer.write("a");
writer.write("abc", 1, 1);
writer.write(99);
writer.flush();
writer.close();
assertThat(writer.toString(), is("abc"));
}
@Test
void testNegativeSize() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new UnsafeStringWriter(-1));
}
@Test
void testAppend() {
UnsafeStringWriter writer = new UnsafeStringWriter();
writer.append('a');
writer.append("abc", 1, 2);
writer.append('c');
writer.flush();
writer.close();
assertThat(writer.toString(), is("abc"));
}
@Test
void testAppendNull() {
UnsafeStringWriter writer = new UnsafeStringWriter();
writer.append(null);
writer.append(null, 0, 4);
writer.flush();
writer.close();
assertThat(writer.toString(), is("nullnull"));
}
@Test
void testWriteNull() throws IOException {
UnsafeStringWriter writer = new UnsafeStringWriter(3);
char[] chars = new char[2];
chars[0] = 'a';
chars[1] = 'b';
writer.write(chars);
writer.write(chars, 0, 1);
writer.flush();
writer.close();
assertThat(writer.toString(), is("aba"));
}
@Test
void testWriteCharWithWrongLength() throws IOException {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeStringWriter writer = new UnsafeStringWriter();
char[] chars = new char[0];
writer.write(chars, 0, 1);
});
}
@Test
void testWriteCharWithWrongCombineLength() throws IOException {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeStringWriter writer = new UnsafeStringWriter();
char[] chars = new char[1];
writer.write(chars, 1, 1);
});
}
}
| 6,446 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
class UnsafeByteArrayOutputStreamTest {
@Test
void testWrongSize() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new UnsafeByteArrayOutputStream(-1));
}
@Test
void testWrite() {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
outputStream.write((int) 'a');
outputStream.write("bc".getBytes(), 0, 2);
assertThat(outputStream.size(), is(3));
assertThat(outputStream.toString(), is("abc"));
}
@Test
void testToByteBuffer() {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
outputStream.write((int) 'a');
ByteBuffer byteBuffer = outputStream.toByteBuffer();
assertThat(byteBuffer.get(), is("a".getBytes()[0]));
}
@Test
void testExtendLengthForBuffer() throws IOException {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
for (int i = 0; i < 10; i++) {
outputStream.write(i);
}
assertThat(outputStream.size(), is(10));
OutputStream stream = mock(OutputStream.class);
outputStream.writeTo(stream);
Mockito.verify(stream).write(any(byte[].class), anyInt(), eq(10));
}
@Test
void testToStringWithCharset() throws IOException {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream();
outputStream.write("Hòa Bình".getBytes());
assertThat(outputStream.toString("UTF-8"), is("Hòa Bình"));
}
}
| 6,447 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class UnsafeByteArrayInputStreamTest {
@Test
void testMark() {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes(), 1);
assertThat(stream.markSupported(), is(true));
stream.mark(2);
stream.read();
assertThat(stream.position(), is(2));
stream.reset();
assertThat(stream.position(), is(1));
}
@Test
void testRead() throws IOException {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
assertThat(stream.read(), is((int) 'a'));
assertThat(stream.available(), is(2));
stream.skip(1);
assertThat(stream.available(), is(1));
byte[] bytes = new byte[1];
int read = stream.read(bytes);
assertThat(read, is(1));
assertThat(bytes, is("c".getBytes()));
stream.reset();
assertThat(stream.position(), is(0));
assertThat(stream.size(), is(3));
stream.position(1);
assertThat(stream.read(), is((int) 'b'));
}
@Test
void testWrongLength() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(new byte[1], 0, 100);
});
}
@Test
void testWrongOffset() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(new byte[1], -1, 1);
});
}
@Test
void testReadEmptyByteArray() {
Assertions.assertThrows(NullPointerException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(null, 0, 1);
});
}
@Test
void testSkipZero() {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
long skip = stream.skip(-1);
assertThat(skip, is(0L));
assertThat(stream.position(), is(0));
}
}
| 6,448 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.log4j.Category;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class DubboAppenderTest {
private LoggingEvent event;
@BeforeEach
public void setUp() throws Exception {
event = mock(LoggingEvent.class);
when(event.getLogger()).thenReturn(mock(Category.class));
when(event.getLevel()).thenReturn(mock(Level.class));
when(event.getThreadName()).thenReturn("thread-name");
when(event.getMessage()).thenReturn("message");
}
@AfterEach
public void tearDown() throws Exception {
DubboAppender.clear();
DubboAppender.doStop();
}
@Test
void testAvailable() {
assumeFalse(DubboAppender.available);
DubboAppender.doStart();
assertThat(DubboAppender.available, is(true));
DubboAppender.doStop();
assertThat(DubboAppender.available, is(false));
}
@Test
void testAppend() {
DubboAppender appender = new DubboAppender();
appender.append(event);
assumeTrue(0 == DubboAppender.logList.size());
DubboAppender.doStart();
appender.append(event);
assertThat(DubboAppender.logList, hasSize(1));
assertThat(DubboAppender.logList.get(0).getLogThread(), equalTo("thread-name"));
}
@Test
void testClear() {
DubboAppender.doStart();
DubboAppender appender = new DubboAppender();
appender.append(event);
assumeTrue(1 == DubboAppender.logList.size());
DubboAppender.clear();
assertThat(DubboAppender.logList, hasSize(0));
}
}
| 6,449 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.extension.DubboInternalLoadingStrategy;
import org.apache.dubbo.common.extension.director.FooAppProvider;
import org.apache.dubbo.common.resource.GlobalResourcesRepository;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link ClassLoaderResourceLoader}
*/
class ClassLoaderResourceLoaderTest {
@Test
void test() throws InterruptedException {
DubboInternalLoadingStrategy dubboInternalLoadingStrategy = new DubboInternalLoadingStrategy();
String directory = dubboInternalLoadingStrategy.directory();
String type = FooAppProvider.class.getName();
String fileName = directory + type;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Map<ClassLoader, Set<URL>> loadResources =
ClassLoaderResourceLoader.loadResources(fileName, Arrays.asList(contextClassLoader));
Assertions.assertTrue(loadResources.containsKey(contextClassLoader));
Assertions.assertTrue(!loadResources.get(contextClassLoader).isEmpty());
// cache
Assertions.assertNotNull(ClassLoaderResourceLoader.getClassLoaderResourcesCache());
loadResources = ClassLoaderResourceLoader.loadResources(fileName, Arrays.asList(contextClassLoader));
Assertions.assertTrue(loadResources.containsKey(contextClassLoader));
Assertions.assertTrue(!loadResources.get(contextClassLoader).isEmpty());
Assertions.assertNotNull(GlobalResourcesRepository.getGlobalReusedDisposables());
ClassLoaderResourceLoader.destroy();
Assertions.assertNull(ClassLoaderResourceLoader.getClassLoaderResourcesCache());
}
}
| 6,450 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MD5UtilsTest {
@Test
void test() {
MD5Utils sharedMd5Utils = new MD5Utils();
final String[] input = {
"provider-appgroup-one/org.apache.dubbo.config.spring.api.HelloService:dubboorg.apache.dubbo.config.spring.api.HelloService{REGISTRY_CLUSTER=registry-one, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-one, interface=org.apache.dubbo.config.spring.api.HelloService, logger=slf4j, metadata-type=remote, methods=sayHello, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}",
"provider-appgroup-two/org.apache.dubbo.config.spring.api.DemoService:dubboorg.apache.dubbo.config.spring.api.DemoService{REGISTRY_CLUSTER=registry-two, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-two, interface=org.apache.dubbo.config.spring.api.DemoService, logger=slf4j, metadata-type=remote, methods=sayName,getBox, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}"
};
final String[] result = {sharedMd5Utils.getMd5(input[0]), new MD5Utils().getMd5(input[1])};
System.out.println("Expected result: " + Arrays.asList(result));
int nThreads = 8;
CountDownLatch latch = new CountDownLatch(nThreads);
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
try {
for (int i = 0; i < nThreads; i++) {
MD5Utils md5Utils = i < nThreads / 2 ? sharedMd5Utils : new MD5Utils();
executorService.submit(new Md5Task(input[i % 2], result[i % 2], md5Utils, latch, errors));
}
latch.await();
Assertions.assertEquals(Collections.EMPTY_LIST, errors);
Assertions.assertEquals(0, latch.getCount());
} catch (Throwable e) {
Assertions.fail(StringUtils.toString(e));
} finally {
executorService.shutdown();
}
}
static class Md5Task implements Runnable {
private final String input;
private final String expected;
private final MD5Utils md5Utils;
private final CountDownLatch latch;
private final List<Throwable> errorCollector;
public Md5Task(
String input,
String expected,
MD5Utils md5Utils,
CountDownLatch latch,
List<Throwable> errorCollector) {
this.input = input;
this.expected = expected;
this.md5Utils = md5Utils;
this.latch = latch;
this.errorCollector = errorCollector;
}
@Override
public void run() {
int i = 0;
long start = System.currentTimeMillis();
try {
for (; i < 200; i++) {
Assertions.assertEquals(expected, md5Utils.getMd5(input));
md5Utils.getMd5("test#" + i);
}
} catch (Throwable e) {
errorCollector.add(e);
e.printStackTrace();
} finally {
long cost = System.currentTimeMillis() - start;
System.out.println("[" + Thread.currentThread().getName() + "] progress: " + i + ", cost: " + cost);
latch.countDown();
}
}
}
}
| 6,451 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class IOUtilsTest {
private static String TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
private InputStream is;
private OutputStream os;
private Reader reader;
private Writer writer;
@BeforeEach
public void setUp() throws Exception {
is = new ByteArrayInputStream(TEXT.getBytes(StandardCharsets.UTF_8));
os = new ByteArrayOutputStream();
reader = new StringReader(TEXT);
writer = new StringWriter();
}
@AfterEach
public void tearDown() throws Exception {
is.close();
os.close();
reader.close();
writer.close();
}
@Test
void testWrite1() throws Exception {
assertThat((int) IOUtils.write(is, os, 16), equalTo(TEXT.length()));
}
@Test
void testWrite2() throws Exception {
assertThat((int) IOUtils.write(reader, writer, 16), equalTo(TEXT.length()));
}
@Test
void testWrite3() throws Exception {
assertThat((int) IOUtils.write(writer, TEXT), equalTo(TEXT.length()));
}
@Test
void testWrite4() throws Exception {
assertThat((int) IOUtils.write(is, os), equalTo(TEXT.length()));
}
@Test
void testWrite5() throws Exception {
assertThat((int) IOUtils.write(reader, writer), equalTo(TEXT.length()));
}
@Test
void testLines(@TempDir Path tmpDir) throws Exception {
File file = tmpDir.getFileName().toAbsolutePath().toFile();
IOUtils.writeLines(file, new String[] {TEXT});
String[] lines = IOUtils.readLines(file);
assertThat(lines.length, equalTo(1));
assertThat(lines[0], equalTo(TEXT));
tmpDir.getFileName().toAbsolutePath().toFile().delete();
}
@Test
void testReadLines() throws Exception {
String[] lines = IOUtils.readLines(is);
assertThat(lines.length, equalTo(1));
assertThat(lines[0], equalTo(TEXT));
}
@Test
void testWriteLines() throws Exception {
IOUtils.writeLines(os, new String[] {TEXT});
ByteArrayOutputStream bos = (ByteArrayOutputStream) os;
assertThat(new String(bos.toByteArray()), equalTo(TEXT + System.lineSeparator()));
}
@Test
void testRead() throws Exception {
assertThat(IOUtils.read(reader), equalTo(TEXT));
}
@Test
void testAppendLines(@TempDir Path tmpDir) throws Exception {
File file = tmpDir.getFileName().toAbsolutePath().toFile();
IOUtils.appendLines(file, new String[] {"a", "b", "c"});
String[] lines = IOUtils.readLines(file);
assertThat(lines.length, equalTo(3));
assertThat(lines[0], equalTo("a"));
assertThat(lines[1], equalTo("b"));
assertThat(lines[2], equalTo("c"));
tmpDir.getFileName().toAbsolutePath().toFile().delete();
}
}
| 6,452 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class TestAllowClassNotifyListener implements AllowClassNotifyListener {
private static final AtomicReference<SerializeCheckStatus> status = new AtomicReference<>();
private static final AtomicReference<Set<String>> allowedList = new AtomicReference<>();
private static final AtomicReference<Set<String>> disAllowedList = new AtomicReference<>();
private static final AtomicBoolean checkSerializable = new AtomicBoolean();
private static final AtomicInteger count = new AtomicInteger(0);
@Override
public void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) {
TestAllowClassNotifyListener.allowedList.set(allowedList);
TestAllowClassNotifyListener.disAllowedList.set(disAllowedList);
count.incrementAndGet();
}
@Override
public void notifyCheckStatus(SerializeCheckStatus status) {
TestAllowClassNotifyListener.status.set(status);
count.incrementAndGet();
}
@Override
public void notifyCheckSerializable(boolean checkSerializable) {
TestAllowClassNotifyListener.checkSerializable.set(checkSerializable);
count.incrementAndGet();
}
public static SerializeCheckStatus getStatus() {
return status.get();
}
public static Set<String> getAllowedList() {
return allowedList.get();
}
public static Set<String> getDisAllowedList() {
return disAllowedList.get();
}
public static boolean isCheckSerializable() {
return checkSerializable.get();
}
public static int getCount() {
return count.get();
}
public static void setCount(int count) {
TestAllowClassNotifyListener.count.set(count);
}
}
| 6,453 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class ReflectUtilsTest {
@Test
void testIsPrimitives() {
assertTrue(ReflectUtils.isPrimitives(boolean[].class));
assertTrue(ReflectUtils.isPrimitives(byte.class));
assertFalse(ReflectUtils.isPrimitive(Map[].class));
}
@Test
void testIsPrimitive() {
assertTrue(ReflectUtils.isPrimitive(boolean.class));
assertTrue(ReflectUtils.isPrimitive(String.class));
assertTrue(ReflectUtils.isPrimitive(Boolean.class));
assertTrue(ReflectUtils.isPrimitive(Character.class));
assertTrue(ReflectUtils.isPrimitive(Number.class));
assertTrue(ReflectUtils.isPrimitive(Date.class));
assertFalse(ReflectUtils.isPrimitive(Map.class));
}
@Test
void testGetBoxedClass() {
assertThat(ReflectUtils.getBoxedClass(int.class), sameInstance(Integer.class));
assertThat(ReflectUtils.getBoxedClass(boolean.class), sameInstance(Boolean.class));
assertThat(ReflectUtils.getBoxedClass(long.class), sameInstance(Long.class));
assertThat(ReflectUtils.getBoxedClass(float.class), sameInstance(Float.class));
assertThat(ReflectUtils.getBoxedClass(double.class), sameInstance(Double.class));
assertThat(ReflectUtils.getBoxedClass(char.class), sameInstance(Character.class));
assertThat(ReflectUtils.getBoxedClass(byte.class), sameInstance(Byte.class));
assertThat(ReflectUtils.getBoxedClass(short.class), sameInstance(Short.class));
assertThat(ReflectUtils.getBoxedClass(String.class), sameInstance(String.class));
}
@Test
void testIsCompatible() {
assertTrue(ReflectUtils.isCompatible(short.class, (short) 1));
assertTrue(ReflectUtils.isCompatible(int.class, 1));
assertTrue(ReflectUtils.isCompatible(double.class, 1.2));
assertTrue(ReflectUtils.isCompatible(Object.class, 1.2));
assertTrue(ReflectUtils.isCompatible(List.class, new ArrayList<String>()));
}
@Test
void testIsCompatibleWithArray() {
assertFalse(ReflectUtils.isCompatible(new Class[] {short.class, int.class}, new Object[] {(short) 1}));
assertFalse(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {"hello"}));
assertTrue(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {1.2}));
}
@Test
void testGetCodeBase() {
assertNull(ReflectUtils.getCodeBase(null));
assertNull(ReflectUtils.getCodeBase(String.class));
assertNotNull(ReflectUtils.getCodeBase(ReflectUtils.class));
}
@Test
void testGetName() {
// getName
assertEquals("boolean", ReflectUtils.getName(boolean.class));
assertEquals("int[][][]", ReflectUtils.getName(int[][][].class));
assertEquals("java.lang.Object[][]", ReflectUtils.getName(Object[][].class));
}
@Test
void testGetDesc() {
// getDesc
assertEquals("Z", ReflectUtils.getDesc(boolean.class));
assertEquals("[[[I", ReflectUtils.getDesc(int[][][].class));
assertEquals("[[Ljava/lang/Object;", ReflectUtils.getDesc(Object[][].class));
}
@Test
void testName2desc() {
// name2desc
assertEquals("Z", ReflectUtils.name2desc(ReflectUtils.getName(boolean.class)));
assertEquals("[[[I", ReflectUtils.name2desc(ReflectUtils.getName(int[][][].class)));
assertEquals("[[Ljava/lang/Object;", ReflectUtils.name2desc(ReflectUtils.getName(Object[][].class)));
}
@Test
void testDesc2name() {
// desc2name
assertEquals("short[]", ReflectUtils.desc2name(ReflectUtils.getDesc(short[].class)));
assertEquals("boolean[]", ReflectUtils.desc2name(ReflectUtils.getDesc(boolean[].class)));
assertEquals("byte[]", ReflectUtils.desc2name(ReflectUtils.getDesc(byte[].class)));
assertEquals("char[]", ReflectUtils.desc2name(ReflectUtils.getDesc(char[].class)));
assertEquals("double[]", ReflectUtils.desc2name(ReflectUtils.getDesc(double[].class)));
assertEquals("float[]", ReflectUtils.desc2name(ReflectUtils.getDesc(float[].class)));
assertEquals("int[]", ReflectUtils.desc2name(ReflectUtils.getDesc(int[].class)));
assertEquals("long[]", ReflectUtils.desc2name(ReflectUtils.getDesc(long[].class)));
assertEquals("int", ReflectUtils.desc2name(ReflectUtils.getDesc(int.class)));
assertEquals("void", ReflectUtils.desc2name(ReflectUtils.getDesc(void.class)));
assertEquals("java.lang.Object[][]", ReflectUtils.desc2name(ReflectUtils.getDesc(Object[][].class)));
}
@Test
void testGetGenericClass() {
assertThat(ReflectUtils.getGenericClass(Foo1.class), sameInstance(String.class));
}
@Test
void testGetGenericClassWithIndex() {
assertThat(ReflectUtils.getGenericClass(Foo1.class, 0), sameInstance(String.class));
assertThat(ReflectUtils.getGenericClass(Foo1.class, 1), sameInstance(Integer.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 0), sameInstance(List.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 1), sameInstance(int.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 0), sameInstance(Foo1.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 1), sameInstance(Foo2.class));
}
@Test
void testGetMethodName() throws Exception {
assertThat(
ReflectUtils.getName(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("java.util.List hello(int[])"));
}
@Test
void testGetSignature() throws Exception {
Method m = Foo2.class.getDeclaredMethod("hello", int[].class);
assertThat(ReflectUtils.getSignature("greeting", m.getParameterTypes()), equalTo("greeting([I)"));
}
@Test
void testGetConstructorName() {
Constructor c = Foo2.class.getConstructors()[0];
assertThat(ReflectUtils.getName(c), equalTo("(java.util.List,int[])"));
}
@Test
void testName2Class() throws Exception {
assertEquals(boolean.class, ReflectUtils.name2class("boolean"));
assertEquals(boolean[].class, ReflectUtils.name2class("boolean[]"));
assertEquals(int[][].class, ReflectUtils.name2class(ReflectUtils.getName(int[][].class)));
assertEquals(ReflectUtilsTest[].class, ReflectUtils.name2class(ReflectUtils.getName(ReflectUtilsTest[].class)));
}
@Test
void testGetDescMethod() throws Exception {
assertThat(
ReflectUtils.getDesc(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("hello([I)Ljava/util/List;"));
}
@Test
void testGetDescConstructor() {
assertThat(ReflectUtils.getDesc(Foo2.class.getConstructors()[0]), equalTo("(Ljava/util/List;[I)V"));
}
@Test
void testGetDescWithoutMethodName() throws Exception {
assertThat(
ReflectUtils.getDescWithoutMethodName(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("([I)Ljava/util/List;"));
}
@Test
void testFindMethodByMethodName1() throws Exception {
assertNotNull(ReflectUtils.findMethodByMethodName(Foo.class, "hello"));
}
@Test
void testFindMethodByMethodName2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ReflectUtils.findMethodByMethodName(Foo2.class, "hello");
});
}
@Test
void testFindConstructor() throws Exception {
Constructor constructor = ReflectUtils.findConstructor(Foo3.class, Foo2.class);
assertNotNull(constructor);
}
@Test
void testIsInstance() {
assertTrue(ReflectUtils.isInstance(new Foo1(), Foo.class.getName()));
}
@Test
void testIsBeanPropertyReadMethod() throws Exception {
Method method = EmptyClass.class.getMethod("getProperty");
assertTrue(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("getProperties");
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("isProperty");
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("getPropertyIndex", int.class);
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
}
@Test
void testGetPropertyNameFromBeanReadMethod() throws Exception {
Method method = EmptyClass.class.getMethod("getProperty");
assertEquals("property", ReflectUtils.getPropertyNameFromBeanReadMethod(method));
method = EmptyClass.class.getMethod("isSet");
assertEquals("set", ReflectUtils.getPropertyNameFromBeanReadMethod(method));
}
@Test
void testIsBeanPropertyWriteMethod() throws Exception {
Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class);
assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method));
method = EmptyClass.class.getMethod("setSet", boolean.class);
assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method));
}
@Test
void testGetPropertyNameFromBeanWriteMethod() throws Exception {
Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class);
assertEquals("property", ReflectUtils.getPropertyNameFromBeanWriteMethod(method));
}
@Test
void testIsPublicInstanceField() throws Exception {
Field field = EmptyClass.class.getDeclaredField("set");
assertTrue(ReflectUtils.isPublicInstanceField(field));
field = EmptyClass.class.getDeclaredField("property");
assertFalse(ReflectUtils.isPublicInstanceField(field));
}
@Test
void testGetBeanPropertyFields() {
Map<String, Field> map = ReflectUtils.getBeanPropertyFields(EmptyClass.class);
assertThat(map.size(), is(2));
assertThat(map, hasKey("set"));
assertThat(map, hasKey("property"));
for (Field f : map.values()) {
if (!f.isAccessible()) {
fail();
}
}
}
@Test
void testGetBeanPropertyReadMethods() {
Map<String, Method> map = ReflectUtils.getBeanPropertyReadMethods(EmptyClass.class);
assertThat(map.size(), is(2));
assertThat(map, hasKey("set"));
assertThat(map, hasKey("property"));
for (Method m : map.values()) {
if (!m.isAccessible()) {
fail();
}
}
}
@Test
void testDesc2Class() throws Exception {
assertEquals(void.class, ReflectUtils.desc2class("V"));
assertEquals(boolean.class, ReflectUtils.desc2class("Z"));
assertEquals(boolean[].class, ReflectUtils.desc2class("[Z"));
assertEquals(byte.class, ReflectUtils.desc2class("B"));
assertEquals(char.class, ReflectUtils.desc2class("C"));
assertEquals(double.class, ReflectUtils.desc2class("D"));
assertEquals(float.class, ReflectUtils.desc2class("F"));
assertEquals(int.class, ReflectUtils.desc2class("I"));
assertEquals(long.class, ReflectUtils.desc2class("J"));
assertEquals(short.class, ReflectUtils.desc2class("S"));
assertEquals(String.class, ReflectUtils.desc2class("Ljava.lang.String;"));
assertEquals(int[][].class, ReflectUtils.desc2class(ReflectUtils.getDesc(int[][].class)));
assertEquals(ReflectUtilsTest[].class, ReflectUtils.desc2class(ReflectUtils.getDesc(ReflectUtilsTest[].class)));
String desc;
Class<?>[] cs;
cs = new Class<?>[] {int.class, getClass(), String.class, int[][].class, boolean[].class};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
cs = new Class<?>[] {};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
cs = new Class<?>[] {void.class, String[].class, int[][].class, ReflectUtilsTest[][].class};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
}
protected void assertSame(Class<?>[] cs1, Class<?>[] cs2) throws Exception {
assertEquals(cs1.length, cs2.length);
for (int i = 0; i < cs1.length; i++) assertEquals(cs1[i], cs2[i]);
}
@Test
void testFindMethodByMethodSignature() throws Exception {
Method m = ReflectUtils.findMethodByMethodSignature(TestedClass.class, "method1", null);
assertEquals("method1", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(int.class, parameterTypes[0]);
}
@Test
void testFindMethodByMethodSignature_override() throws Exception {
{
Method m =
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", new String[] {"int"});
assertEquals("overrideMethod", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(int.class, parameterTypes[0]);
}
{
Method m = ReflectUtils.findMethodByMethodSignature(
TestedClass.class, "overrideMethod", new String[] {"java.lang.Integer"});
assertEquals("overrideMethod", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(Integer.class, parameterTypes[0]);
}
}
@Test
void testFindMethodByMethodSignatureOverrideMoreThan1() throws Exception {
try {
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", null);
fail();
} catch (IllegalStateException expected) {
assertThat(expected.getMessage(), containsString("Not unique method for method name("));
}
}
@Test
void testFindMethodByMethodSignatureNotFound() throws Exception {
try {
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "doesNotExist", null);
fail();
} catch (NoSuchMethodException expected) {
assertThat(expected.getMessage(), containsString("No such method "));
assertThat(expected.getMessage(), containsString("in class"));
}
}
@Test
void testGetEmptyObject() {
assertTrue(ReflectUtils.getEmptyObject(Collection.class) instanceof Collection);
assertTrue(ReflectUtils.getEmptyObject(List.class) instanceof List);
assertTrue(ReflectUtils.getEmptyObject(Set.class) instanceof Set);
assertTrue(ReflectUtils.getEmptyObject(Map.class) instanceof Map);
assertTrue(ReflectUtils.getEmptyObject(Object[].class) instanceof Object[]);
assertEquals("", ReflectUtils.getEmptyObject(String.class));
assertEquals((short) 0, ReflectUtils.getEmptyObject(short.class));
assertEquals((byte) 0, ReflectUtils.getEmptyObject(byte.class));
assertEquals(0, ReflectUtils.getEmptyObject(int.class));
assertEquals(0L, ReflectUtils.getEmptyObject(long.class));
assertEquals((float) 0, ReflectUtils.getEmptyObject(float.class));
assertEquals((double) 0, ReflectUtils.getEmptyObject(double.class));
assertEquals('\0', ReflectUtils.getEmptyObject(char.class));
assertEquals(Boolean.FALSE, ReflectUtils.getEmptyObject(boolean.class));
EmptyClass object = (EmptyClass) ReflectUtils.getEmptyObject(EmptyClass.class);
assertNotNull(object);
assertNotNull(object.getProperty());
}
@Test
void testForName1() {
assertThat(ReflectUtils.forName(ReflectUtils.class.getName()), sameInstance(ReflectUtils.class));
}
@Test
void testForName2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ReflectUtils.forName("a.c.d.e.F");
});
}
@Test
void testGetReturnTypes() throws Exception {
Class<TypeClass> clazz = TypeClass.class;
Type[] types = ReflectUtils.getReturnTypes(clazz.getMethod("getFuture"));
Assertions.assertEquals("java.lang.String", types[0].getTypeName());
Assertions.assertEquals("java.lang.String", types[1].getTypeName());
Type[] types1 = ReflectUtils.getReturnTypes(clazz.getMethod("getString"));
Assertions.assertEquals("java.lang.String", types1[0].getTypeName());
Assertions.assertEquals("java.lang.String", types1[1].getTypeName());
Type[] types2 = ReflectUtils.getReturnTypes(clazz.getMethod("getT"));
Assertions.assertEquals("java.lang.String", types2[0].getTypeName());
Assertions.assertEquals("T", types2[1].getTypeName());
Type[] types3 = ReflectUtils.getReturnTypes(clazz.getMethod("getS"));
Assertions.assertEquals("java.lang.Object", types3[0].getTypeName());
Assertions.assertEquals("S", types3[1].getTypeName());
Type[] types4 = ReflectUtils.getReturnTypes(clazz.getMethod("getListFuture"));
Assertions.assertEquals("java.util.List", types4[0].getTypeName());
Assertions.assertEquals("java.util.List<java.lang.String>", types4[1].getTypeName());
Type[] types5 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericWithUpperFuture"));
// T extends String, the first arg should be the upper bound of param
Assertions.assertEquals("java.lang.String", types5[0].getTypeName());
Assertions.assertEquals("T", types5[1].getTypeName());
Type[] types6 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericFuture"));
// default upper bound is Object
Assertions.assertEquals("java.lang.Object", types6[0].getTypeName());
Assertions.assertEquals("S", types6[1].getTypeName());
}
public interface TypeClass<T extends String, S> {
CompletableFuture<String> getFuture();
String getString();
T getT();
S getS();
CompletableFuture<List<String>> getListFuture();
CompletableFuture<T> getGenericWithUpperFuture();
CompletableFuture<S> getGenericFuture();
}
public static class EmptyClass {
private EmptyProperty property;
public boolean set;
public static String s;
private transient int i;
public EmptyProperty getProperty() {
return property;
}
public EmptyProperty getPropertyIndex(int i) {
return property;
}
public static EmptyProperty getProperties() {
return null;
}
public void isProperty() {}
public boolean isSet() {
return set;
}
public void setProperty(EmptyProperty property) {
this.property = property;
}
public void setSet(boolean set) {
this.set = set;
}
}
public static class EmptyProperty {}
static class TestedClass {
public void method1(int x) {}
public void overrideMethod(int x) {}
public void overrideMethod(Integer x) {}
public void overrideMethod(String s) {}
public void overrideMethod(String s1, String s2) {}
}
interface Foo<A, B> {
A hello(B b);
}
static class Foo1 implements Foo<String, Integer> {
@Override
public String hello(Integer integer) {
return null;
}
}
static class Foo2 implements Foo<List<String>, int[]> {
public Foo2(List<String> list, int[] ints) {}
@Override
public List<String> hello(int[] ints) {
return null;
}
}
static class Foo3 implements Foo<Foo1, Foo2> {
public Foo3(Foo foo) {}
@Override
public Foo1 hello(Foo2 foo2) {
return null;
}
}
}
| 6,454 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.utils.AnnotationUtils.excludedType;
import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues;
import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAllDeclaredAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAllMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttributes;
import static org.apache.dubbo.common.utils.AnnotationUtils.getDeclaredAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getDefaultValue;
import static org.apache.dubbo.common.utils.AnnotationUtils.getMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getValue;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnyAnnotationPresent;
import static org.apache.dubbo.common.utils.AnnotationUtils.isSameType;
import static org.apache.dubbo.common.utils.AnnotationUtils.isType;
import static org.apache.dubbo.common.utils.MethodUtils.findMethod;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link AnnotationUtils} Test
*
* @since 2.7.6
*/
class AnnotationUtilsTest {
@Test
void testIsType() {
// null checking
assertFalse(isType(null));
// Method checking
assertFalse(isType(findMethod(A.class, "execute")));
// Class checking
assertTrue(isType(A.class));
}
@Test
void testIsSameType() {
assertTrue(isSameType(A.class.getAnnotation(Service.class), Service.class));
assertFalse(isSameType(A.class.getAnnotation(Service.class), Deprecated.class));
assertFalse(isSameType(A.class.getAnnotation(Service.class), null));
assertFalse(isSameType(null, Deprecated.class));
assertFalse(isSameType(null, null));
}
@Test
void testExcludedType() {
assertFalse(excludedType(Service.class).test(A.class.getAnnotation(Service.class)));
assertTrue(excludedType(Service.class).test(A.class.getAnnotation(Deprecated.class)));
}
@Test
void testGetAttribute() {
Annotation annotation = A.class.getAnnotation(Service.class);
assertEquals("java.lang.CharSequence", getAttribute(annotation, "interfaceName"));
assertEquals(CharSequence.class, getAttribute(annotation, "interfaceClass"));
assertEquals("", getAttribute(annotation, "version"));
assertEquals("", getAttribute(annotation, "group"));
assertEquals("", getAttribute(annotation, "path"));
assertEquals(true, getAttribute(annotation, "export"));
assertEquals(false, getAttribute(annotation, "deprecated"));
}
@Test
void testGetAttributesMap() {
Annotation annotation = A.class.getAnnotation(Service.class);
Map<String, Object> attributes = getAttributes(annotation, false);
assertEquals("java.lang.CharSequence", attributes.get("interfaceName"));
assertEquals(CharSequence.class, attributes.get("interfaceClass"));
assertEquals("", attributes.get("group"));
assertEquals(getDefaultValue(annotation, "export"), attributes.get("export"));
Map<String, Object> filteredAttributes = filterDefaultValues(annotation, attributes);
assertEquals(2, filteredAttributes.size());
assertEquals("java.lang.CharSequence", filteredAttributes.get("interfaceName"));
assertEquals(CharSequence.class, filteredAttributes.get("interfaceClass"));
assertFalse(filteredAttributes.containsKey("group"));
assertFalse(filteredAttributes.containsKey("export"));
Map<String, Object> nonDefaultAttributes = getAttributes(annotation, true);
assertEquals(nonDefaultAttributes, filteredAttributes);
}
@Test
void testGetValue() {
Adaptive adaptive = A.class.getAnnotation(Adaptive.class);
String[] value = getValue(adaptive);
assertEquals(asList("a", "b", "c"), asList(value));
}
@Test
void testGetDeclaredAnnotations() {
List<Annotation> annotations = getDeclaredAnnotations(A.class);
assertADeclaredAnnotations(annotations, 0);
annotations = getDeclaredAnnotations(A.class, a -> isSameType(a, Service.class));
assertEquals(1, annotations.size());
Service service = (Service) annotations.get(0);
assertEquals("java.lang.CharSequence", service.interfaceName());
assertEquals(CharSequence.class, service.interfaceClass());
}
@Test
void testGetAllDeclaredAnnotations() {
List<Annotation> annotations = getAllDeclaredAnnotations(A.class);
assertADeclaredAnnotations(annotations, 0);
annotations = getAllDeclaredAnnotations(B.class);
assertTrue(isSameType(annotations.get(0), Service5.class));
assertADeclaredAnnotations(annotations, 1);
annotations = new LinkedList<>(getAllDeclaredAnnotations(C.class));
assertTrue(isSameType(annotations.get(0), MyAdaptive.class));
assertTrue(isSameType(annotations.get(1), Service5.class));
assertADeclaredAnnotations(annotations, 2);
annotations = getAllDeclaredAnnotations(findMethod(A.class, "execute"));
MyAdaptive myAdaptive = (MyAdaptive) annotations.get(0);
assertArrayEquals(new String[] {"e"}, myAdaptive.value());
annotations = getAllDeclaredAnnotations(findMethod(B.class, "execute"));
Adaptive adaptive = (Adaptive) annotations.get(0);
assertArrayEquals(new String[] {"f"}, adaptive.value());
}
@Test
void testGetMetaAnnotations() {
List<Annotation> metaAnnotations = getMetaAnnotations(Service.class, a -> isSameType(a, Inherited.class));
assertEquals(1, metaAnnotations.size());
assertEquals(Inherited.class, metaAnnotations.get(0).annotationType());
metaAnnotations = getMetaAnnotations(Service.class);
HashSet<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> set2 = new HashSet<>();
set2.add(Inherited.class);
set2.add(Deprecated.class);
assertEquals(2, metaAnnotations.size());
assertEquals(set1, set2);
}
@Test
void testGetAllMetaAnnotations() {
List<Annotation> metaAnnotations = getAllMetaAnnotations(Service5.class);
int offset = 0;
HashSet<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> set2 = new HashSet<>();
set2.add(Inherited.class);
set2.add(DubboService.class);
set2.add(Service4.class);
set2.add(Service3.class);
set2.add(Service2.class);
assertEquals(9, metaAnnotations.size());
assertEquals(set1, set2);
metaAnnotations = getAllMetaAnnotations(MyAdaptive.class);
HashSet<Object> set3 = new HashSet<>();
metaAnnotations.forEach(t -> set3.add(t.annotationType()));
HashSet<Object> set4 = new HashSet<>();
metaAnnotations.forEach(t -> set3.add(t.annotationType()));
set4.add(Inherited.class);
set4.add(Adaptive.class);
assertEquals(2, metaAnnotations.size());
assertEquals(set3, set4);
}
@Test
void testIsAnnotationPresent() {
assertTrue(isAnnotationPresent(A.class, true, Service.class));
// assertTrue(isAnnotationPresent(A.class, true, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnnotationPresent(A.class, Service.class));
assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service"));
// assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class));
assertTrue(isAnnotationPresent(A.class, Deprecated.class));
}
@Test
void testIsAnyAnnotationPresent() {
// assertTrue(isAnyAnnotationPresent(A.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class));
// assertTrue(isAnyAnnotationPresent(A.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class));
// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class,
// Deprecated.class));
assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class));
assertTrue(isAnyAnnotationPresent(A.class, Service.class));
// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class));
}
@Test
void testGetAnnotation() {
assertNotNull(getAnnotation(A.class, "org.apache.dubbo.config.annotation.Service"));
// assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service"));
assertNotNull(getAnnotation(A.class, "org.apache.dubbo.common.extension.Adaptive"));
assertNull(getAnnotation(A.class, "java.lang.Deprecated"));
assertNull(getAnnotation(A.class, "java.lang.String"));
assertNull(getAnnotation(A.class, "NotExistedClass"));
}
@Test
void testFindAnnotation() {
Service service = findAnnotation(A.class, Service.class);
assertEquals("java.lang.CharSequence", service.interfaceName());
assertEquals(CharSequence.class, service.interfaceClass());
service = findAnnotation(B.class, Service.class);
assertEquals(CharSequence.class, service.interfaceClass());
}
@Test
void testFindMetaAnnotations() {
List<DubboService> services = findMetaAnnotations(B.class, DubboService.class);
assertEquals(1, services.size());
DubboService service = services.get(0);
assertEquals("", service.interfaceName());
assertEquals(Cloneable.class, service.interfaceClass());
services = findMetaAnnotations(Service5.class, DubboService.class);
assertEquals(1, services.size());
service = services.get(0);
assertEquals("", service.interfaceName());
assertEquals(Cloneable.class, service.interfaceClass());
}
@Test
void testFindMetaAnnotation() {
DubboService service = findMetaAnnotation(B.class, DubboService.class);
assertEquals(Cloneable.class, service.interfaceClass());
service = findMetaAnnotation(B.class, "org.apache.dubbo.config.annotation.DubboService");
assertEquals(Cloneable.class, service.interfaceClass());
service = findMetaAnnotation(Service5.class, DubboService.class);
assertEquals(Cloneable.class, service.interfaceClass());
}
@Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class)
@Adaptive(value = {"a", "b", "c"})
static class A {
@MyAdaptive("e")
public void execute() {}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@DubboService(interfaceClass = Cloneable.class)
@interface Service2 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service2
@interface Service3 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service3
@interface Service4 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service4
@interface Service5 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@Adaptive
@interface MyAdaptive {
String[] value() default {};
}
@Service5
static class B extends A {
@Adaptive("f")
@Override
public void execute() {}
}
@MyAdaptive
static class C extends B {}
private void assertADeclaredAnnotations(List<Annotation> annotations, int offset) {
int size = 2 + offset;
assertEquals(size, annotations.size());
boolean apacheServiceFound = false;
boolean adaptiveFound = false;
for (Annotation annotation : annotations) {
if (!apacheServiceFound && (annotation instanceof Service)) {
assertEquals("java.lang.CharSequence", ((Service) annotation).interfaceName());
assertEquals(CharSequence.class, ((Service) annotation).interfaceClass());
apacheServiceFound = true;
continue;
}
if (!adaptiveFound && (annotation instanceof Adaptive)) {
assertArrayEquals(new String[] {"a", "b", "c"}, ((Adaptive) annotation).value());
adaptiveFound = true;
continue;
}
}
assertTrue(apacheServiceFound && adaptiveFound);
}
}
| 6,455 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.log4j.Level;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class LogTest {
@Test
void testLogName() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogName("log-name");
log2.setLogName("log-name");
log3.setLogName("log-name-other");
assertThat(log1.getLogName(), equalTo("log-name"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogLevel() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogLevel(Level.ALL);
log2.setLogLevel(Level.ALL);
log3.setLogLevel(Level.DEBUG);
assertThat(log1.getLogLevel(), is(Level.ALL));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogMessage() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogMessage("log-message");
log2.setLogMessage("log-message");
log3.setLogMessage("log-message-other");
assertThat(log1.getLogMessage(), equalTo("log-message"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogThread() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogThread("log-thread");
log2.setLogThread("log-thread");
log3.setLogThread("log-thread-other");
assertThat(log1.getLogThread(), equalTo("log-thread"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
}
| 6,456 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.Matchers.startsWith;
import static org.mockito.Mockito.verify;
class ClassUtilsTest {
@Test
void testForNameWithThreadContextClassLoader() throws Exception {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader classLoader = Mockito.mock(ClassLoader.class);
Thread.currentThread().setContextClassLoader(classLoader);
ClassUtils.forNameWithThreadContextClassLoader("a.b.c.D");
verify(classLoader).loadClass("a.b.c.D");
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
@Test
void tetForNameWithCallerClassLoader() throws Exception {
Class c = ClassUtils.forNameWithCallerClassLoader(ClassUtils.class.getName(), ClassUtilsTest.class);
assertThat(c == ClassUtils.class, is(true));
}
@Test
void testGetCallerClassLoader() {
assertThat(
ClassUtils.getCallerClassLoader(ClassUtilsTest.class),
sameInstance(ClassUtilsTest.class.getClassLoader()));
}
@Test
void testGetClassLoader1() {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(oldClassLoader));
Thread.currentThread().setContextClassLoader(null);
assertThat(
ClassUtils.getClassLoader(ClassUtilsTest.class),
sameInstance(ClassUtilsTest.class.getClassLoader()));
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
@Test
void testGetClassLoader2() {
assertThat(ClassUtils.getClassLoader(), sameInstance(ClassUtils.class.getClassLoader()));
}
@Test
void testForName1() throws Exception {
assertThat(ClassUtils.forName(ClassUtilsTest.class.getName()) == ClassUtilsTest.class, is(true));
}
@Test
void testForName2() throws Exception {
assertThat(ClassUtils.forName("byte") == byte.class, is(true));
assertThat(ClassUtils.forName("java.lang.String[]") == String[].class, is(true));
assertThat(ClassUtils.forName("[Ljava.lang.String;") == String[].class, is(true));
}
@Test
void testForName3() throws Exception {
ClassLoader classLoader = Mockito.mock(ClassLoader.class);
ClassUtils.forName("a.b.c.D", classLoader);
verify(classLoader).loadClass("a.b.c.D");
}
@Test
void testResolvePrimitiveClassName() {
assertThat(ClassUtils.resolvePrimitiveClassName("boolean") == boolean.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("byte") == byte.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("char") == char.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("double") == double.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("float") == float.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("int") == int.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("long") == long.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("short") == short.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[Z") == boolean[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[B") == byte[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[C") == char[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[D") == double[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[F") == float[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[I") == int[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[J") == long[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[S") == short[].class, is(true));
}
@Test
void testToShortString() {
assertThat(ClassUtils.toShortString(null), equalTo("null"));
assertThat(ClassUtils.toShortString(new ClassUtilsTest()), startsWith("ClassUtilsTest@"));
}
@Test
void testConvertPrimitive() {
assertThat(ClassUtils.convertPrimitive(char.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(char.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(char.class, "6"), equalTo(Character.valueOf('6')));
assertThat(ClassUtils.convertPrimitive(boolean.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(boolean.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(boolean.class, "true"), equalTo(Boolean.TRUE));
assertThat(ClassUtils.convertPrimitive(byte.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(byte.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(byte.class, "127"), equalTo(Byte.MAX_VALUE));
assertThat(ClassUtils.convertPrimitive(short.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(short.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(short.class, "32767"), equalTo(Short.MAX_VALUE));
assertThat(ClassUtils.convertPrimitive(int.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(int.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(int.class, "6"), equalTo(6));
assertThat(ClassUtils.convertPrimitive(long.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(long.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(long.class, "6"), equalTo(Long.valueOf(6)));
assertThat(ClassUtils.convertPrimitive(float.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(float.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(float.class, "1.1"), equalTo(Float.valueOf(1.1F)));
assertThat(ClassUtils.convertPrimitive(double.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(double.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(double.class, "10.1"), equalTo(Double.valueOf(10.1)));
}
}
| 6,457 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.net.Socket;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class DefaultSerializeClassCheckerTest {
@BeforeEach
void setUp() {
FrameworkModel.destroyAll();
}
@AfterEach
void tearDown() {
FrameworkModel.destroyAll();
}
@Test
void testCommon() throws ClassNotFoundException {
FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.setCheckStatus(SerializeCheckStatus.WARN);
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), LinkedList.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Integer.class.getName());
defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), int.class.getName());
}
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Socket.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Socket.class.getName()));
}
@Test
void testAddAllow() throws ClassNotFoundException {
System.setProperty(
CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST,
ReentrantReadWriteLock.WriteLock.class.getName() + ","
+ ReentrantReadWriteLock.ReadLock.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName());
}
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST);
}
@Test
void testAddBlock() {
System.setProperty(
CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST, Runtime.class.getName() + "," + Thread.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Runtime.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Runtime.class.getName()));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Thread.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Thread.class.getName()));
}
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST);
}
@Test
void testBlockAll() throws ClassNotFoundException {
System.setProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL, "true");
System.setProperty(
CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST, ReentrantReadWriteLock.WriteLock.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName());
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(),
ReentrantReadWriteLock.ReadLock.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(ReentrantReadWriteLock.ReadLock.class.getName()));
}
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL);
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST);
}
@Test
void testStatus() throws ClassNotFoundException {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
Assertions.assertEquals(
Integer.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Integer.class.getName()));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(ReentrantReadWriteLock.class.getName()));
ssm.setCheckStatus(SerializeCheckStatus.WARN);
Assertions.assertEquals(
ReentrantReadWriteLock.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()));
ssm.setCheckStatus(SerializeCheckStatus.DISABLE);
Assertions.assertEquals(
ReentrantReadWriteLock.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()));
}
}
| 6,458 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.Assert.notEmptyString;
import static org.apache.dubbo.common.utils.Assert.notNull;
class AssertTest {
@Test
void testNotNull1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> notNull(null, "null object"));
}
@Test
void testNotNull2() {
Assertions.assertThrows(
IllegalStateException.class, () -> notNull(null, new IllegalStateException("null object")));
}
@Test
void testNotNullWhenInputNotNull1() {
notNull(new Object(), "null object");
}
@Test
void testNotNullWhenInputNotNull2() {
notNull(new Object(), new IllegalStateException("null object"));
}
@Test
void testNotNullString() {
Assertions.assertThrows(IllegalArgumentException.class, () -> notEmptyString(null, "Message can't be null"));
}
@Test
void testNotEmptyString() {
Assertions.assertThrows(
IllegalArgumentException.class, () -> notEmptyString("", "Message can't be null or empty"));
}
@Test
void testNotNullNotEmptyString() {
notEmptyString("abcd", "Message can'be null or empty");
}
}
| 6,459 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringConstantFieldValuePredicate} Test
*
* @since 2.7.8
*/
class StringConstantFieldValuePredicateTest {
public static final String S1 = "1";
public static final Object O1 = "2";
public static final Object O2 = 3;
@Test
void test() {
Predicate<String> predicate = of(getClass());
assertTrue(predicate.test("1"));
assertTrue(predicate.test("2"));
assertFalse(predicate.test("3"));
}
}
| 6,460 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CompatibleTypeUtilsTest {
@SuppressWarnings("unchecked")
@Test
void testCompatibleTypeConvert() throws Exception {
Object result;
{
Object input = new Object();
result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class);
assertSame(input, result);
result = CompatibleTypeUtils.compatibleTypeConvert(input, null);
assertSame(input, result);
result = CompatibleTypeUtils.compatibleTypeConvert(null, Date.class);
assertNull(result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert("a", char.class);
assertEquals(Character.valueOf('a'), (Character) result);
result = CompatibleTypeUtils.compatibleTypeConvert("A", MyEnum.class);
assertEquals(MyEnum.A, (MyEnum) result);
result = CompatibleTypeUtils.compatibleTypeConvert("3", BigInteger.class);
assertEquals(new BigInteger("3"), (BigInteger) result);
result = CompatibleTypeUtils.compatibleTypeConvert("3", BigDecimal.class);
assertEquals(new BigDecimal("3"), (BigDecimal) result);
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", Date.class);
assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-12-11 12:24:12"), (Date) result);
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Date.class);
assertEquals(new SimpleDateFormat("yyyy-MM-dd").format((java.sql.Date) result), "2011-12-11");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Time.class);
assertEquals(new SimpleDateFormat("HH:mm:ss").format((java.sql.Time) result), "12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Timestamp.class);
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.sql.Timestamp) result),
"2011-12-11 12:24:12");
result =
CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalDateTime.class);
assertEquals(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((java.time.LocalDateTime) result),
"2011-12-11 12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalTime.class);
assertEquals(DateTimeFormatter.ofPattern("HH:mm:ss").format((java.time.LocalTime) result), "12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11", java.time.LocalDate.class);
assertEquals(DateTimeFormatter.ofPattern("yyyy-MM-dd").format((java.time.LocalDate) result), "2011-12-11");
result = CompatibleTypeUtils.compatibleTypeConvert("ab", char[].class);
assertEquals(2, ((char[]) result).length);
assertEquals('a', ((char[]) result)[0]);
assertEquals('b', ((char[]) result)[1]);
result = CompatibleTypeUtils.compatibleTypeConvert("", char[].class);
assertEquals(0, ((char[]) result).length);
result = CompatibleTypeUtils.compatibleTypeConvert(null, char[].class);
assertNull(result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert(3, byte.class);
assertEquals(Byte.valueOf((byte) 3), (Byte) result);
result = CompatibleTypeUtils.compatibleTypeConvert((byte) 3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, short.class);
assertEquals(Short.valueOf((short) 3), (Short) result);
result = CompatibleTypeUtils.compatibleTypeConvert((short) 3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, long.class);
assertEquals(Long.valueOf(3), (Long) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3L, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3L, BigInteger.class);
assertEquals(BigInteger.valueOf(3L), (BigInteger) result);
result = CompatibleTypeUtils.compatibleTypeConvert(BigInteger.valueOf(3L), int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert(3D, float.class);
assertEquals(Float.valueOf(3), (Float) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3F, double.class);
assertEquals(Double.valueOf(3), (Double) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3D, double.class);
assertEquals(Double.valueOf(3), (Double) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3D, BigDecimal.class);
assertEquals(BigDecimal.valueOf(3D), (BigDecimal) result);
result = CompatibleTypeUtils.compatibleTypeConvert(BigDecimal.valueOf(3D), double.class);
assertEquals(Double.valueOf(3), (Double) result);
}
{
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Set<String> set = new HashSet<String>();
set.add("a");
set.add("b");
String[] array = new String[] {"a", "b"};
result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class);
assertEquals(ArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, List.class);
assertEquals(ArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, CopyOnWriteArrayList.class);
assertEquals(CopyOnWriteArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, CopyOnWriteArrayList.class);
assertEquals(CopyOnWriteArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, String[].class);
assertEquals(String[].class, result.getClass());
assertEquals(2, ((String[]) result).length);
assertTrue(((String[]) result)[0].equals("a") || ((String[]) result)[0].equals("b"));
assertTrue(((String[]) result)[1].equals("a") || ((String[]) result)[1].equals("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, Set.class);
assertEquals(HashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, Set.class);
assertEquals(HashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, ConcurrentHashSet.class);
assertEquals(ConcurrentHashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, ConcurrentHashSet.class);
assertEquals(ConcurrentHashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, String[].class);
assertEquals(String[].class, result.getClass());
assertEquals(2, ((String[]) result).length);
assertTrue(((String[]) result)[0].equals("a"));
assertTrue(((String[]) result)[1].equals("b"));
}
}
}
| 6,461 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_NETWORK_IGNORED_INTERFACE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class NetUtilsTest {
@Test
void testGetRandomPort() {
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
assertThat(NetUtils.getRandomPort(), greaterThanOrEqualTo(30000));
}
@Test
void testGetAvailablePort() {
assertThat(NetUtils.getAvailablePort(), greaterThan(0));
assertThat(NetUtils.getAvailablePort(12345), greaterThanOrEqualTo(12345));
assertThat(NetUtils.getAvailablePort(-1), greaterThanOrEqualTo(0));
}
@Test
void testValidAddress() {
assertTrue(NetUtils.isValidAddress("10.20.130.230:20880"));
assertFalse(NetUtils.isValidAddress("10.20.130.230"));
assertFalse(NetUtils.isValidAddress("10.20.130.230:666666"));
}
@Test
void testIsInvalidPort() {
assertTrue(NetUtils.isInvalidPort(0));
assertTrue(NetUtils.isInvalidPort(65536));
assertFalse(NetUtils.isInvalidPort(1024));
}
@Test
void testIsLocalHost() {
assertTrue(NetUtils.isLocalHost("localhost"));
assertTrue(NetUtils.isLocalHost("127.1.2.3"));
assertFalse(NetUtils.isLocalHost("128.1.2.3"));
}
@Test
void testIsAnyHost() {
assertTrue(NetUtils.isAnyHost("0.0.0.0"));
assertFalse(NetUtils.isAnyHost("1.1.1.1"));
}
@Test
void testIsInvalidLocalHost() {
assertTrue(NetUtils.isInvalidLocalHost(null));
assertTrue(NetUtils.isInvalidLocalHost(""));
assertTrue(NetUtils.isInvalidLocalHost("localhost"));
assertTrue(NetUtils.isInvalidLocalHost("0.0.0.0"));
assertTrue(NetUtils.isInvalidLocalHost("127.1.2.3"));
assertTrue(NetUtils.isInvalidLocalHost("127.0.0.1"));
assertFalse(NetUtils.isInvalidLocalHost("128.0.0.1"));
}
@Test
void testIsValidLocalHost() {
assertTrue(NetUtils.isValidLocalHost("1.2.3.4"));
assertTrue(NetUtils.isValidLocalHost("128.0.0.1"));
}
@Test
void testGetLocalSocketAddress() {
InetSocketAddress address = NetUtils.getLocalSocketAddress("localhost", 12345);
assertTrue(address.getAddress().isAnyLocalAddress());
assertEquals(address.getPort(), 12345);
address = NetUtils.getLocalSocketAddress("dubbo-addr", 12345);
assertEquals(address.getHostName(), "dubbo-addr");
assertEquals(address.getPort(), 12345);
}
@Test
void testIsValidAddress() {
assertFalse(NetUtils.isValidV4Address((InetAddress) null));
InetAddress address = mock(InetAddress.class);
when(address.isLoopbackAddress()).thenReturn(true);
assertFalse(NetUtils.isValidV4Address(address));
address = mock(InetAddress.class);
when(address.getHostAddress()).thenReturn("localhost");
assertFalse(NetUtils.isValidV4Address(address));
address = mock(InetAddress.class);
when(address.getHostAddress()).thenReturn("0.0.0.0");
assertFalse(NetUtils.isValidV4Address(address));
address = mock(InetAddress.class);
when(address.getHostAddress()).thenReturn("127.0.0.1");
assertFalse(NetUtils.isValidV4Address(address));
address = mock(InetAddress.class);
when(address.getHostAddress()).thenReturn("1.2.3.4");
assertTrue(NetUtils.isValidV4Address(address));
}
@Test
void testGetLocalHost() {
assertNotNull(NetUtils.getLocalHost());
}
@Test
void testGetLocalAddress() {
InetAddress address = NetUtils.getLocalAddress();
assertNotNull(address);
assertTrue(NetUtils.isValidLocalHost(address.getHostAddress()));
}
@Test
void testFilterLocalHost() {
assertNull(NetUtils.filterLocalHost(null));
assertEquals(NetUtils.filterLocalHost(""), "");
String host = NetUtils.filterLocalHost("dubbo://127.0.0.1:8080/foo");
assertThat(host, equalTo("dubbo://" + NetUtils.getLocalHost() + ":8080/foo"));
host = NetUtils.filterLocalHost("127.0.0.1:8080");
assertThat(host, equalTo(NetUtils.getLocalHost() + ":8080"));
host = NetUtils.filterLocalHost("0.0.0.0");
assertThat(host, equalTo(NetUtils.getLocalHost()));
host = NetUtils.filterLocalHost("88.88.88.88");
assertThat(host, equalTo(host));
}
@Test
void testGetHostName() {
assertNotNull(NetUtils.getHostName("127.0.0.1"));
}
@Test
void testGetIpByHost() {
assertThat(NetUtils.getIpByHost("localhost"), equalTo("127.0.0.1"));
assertThat(NetUtils.getIpByHost("dubbo.local"), equalTo("dubbo.local"));
}
@Test
void testToAddressString() {
InetAddress address = mock(InetAddress.class);
when(address.getHostAddress()).thenReturn("dubbo");
InetSocketAddress socketAddress = new InetSocketAddress(address, 1234);
assertThat(NetUtils.toAddressString(socketAddress), equalTo("dubbo:1234"));
}
@Test
void testToAddress() {
InetSocketAddress address = NetUtils.toAddress("localhost:1234");
assertThat(address.getHostName(), equalTo("localhost"));
assertThat(address.getPort(), equalTo(1234));
address = NetUtils.toAddress("localhost");
assertThat(address.getHostName(), equalTo("localhost"));
assertThat(address.getPort(), equalTo(0));
}
@Test
void testToURL() {
String url = NetUtils.toURL("dubbo", "host", 1234, "foo");
assertThat(url, equalTo("dubbo://host:1234/foo"));
}
@Test
void testIsValidV6Address() {
String saved = System.getProperty("java.net.preferIPv6Addresses", "false");
System.setProperty("java.net.preferIPv6Addresses", "true");
InetAddress address = NetUtils.getLocalAddress();
boolean isPreferIPV6Address = NetUtils.isPreferIPV6Address();
// Restore system property to previous value before executing test
System.setProperty("java.net.preferIPv6Addresses", saved);
assumeTrue(address instanceof Inet6Address);
assertThat(isPreferIPV6Address, equalTo(true));
}
/**
* Mockito starts to support mocking final classes since 2.1.0
* see https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#unmockable
* But enable it will cause other UT to fail.
* Therefore, currently disabling this UT.
*/
@Disabled
@Test
void testNormalizeV6Address() {
Inet6Address address = mock(Inet6Address.class);
when(address.getHostAddress()).thenReturn("fe80:0:0:0:894:aeec:f37d:23e1%en0");
when(address.getScopeId()).thenReturn(5);
InetAddress normalized = NetUtils.normalizeV6Address(address);
assertThat(normalized.getHostAddress(), equalTo("fe80:0:0:0:894:aeec:f37d:23e1%5"));
}
@Test
void testMatchIpRangeMatchWhenIpv4() throws UnknownHostException {
assertTrue(NetUtils.matchIpRange("*.*.*.*", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.*", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.63", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.1-65", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.1-61", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.62", "192.168.1.63", 90));
}
@Test
void testMatchIpRangeMatchWhenIpv6() throws UnknownHostException {
assertTrue(NetUtils.matchIpRange("*.*.*.*", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:*", "234e:0:4567::3d:ff", 90));
assertTrue(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:ee", "234e:0:4567::3d:ee", 90));
assertTrue(NetUtils.matchIpRange("234e:0:4567::3d:ee", "234e:0:4567::3d:ee", 90));
assertTrue(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:0-ff", "234e:0:4567::3d:ee", 90));
assertTrue(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:0-ee", "234e:0:4567::3d:ee", 90));
assertFalse(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:ff", "234e:0:4567::3d:ee", 90));
assertFalse(NetUtils.matchIpRange("234e:0:4567:0:0:0:3d:0-ea", "234e:0:4567::3d:ee", 90));
}
@Test
void testMatchIpRangeMatchWhenIpv6Exception() {
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> NetUtils.matchIpRange("234e:0:4567::3d:*", "234e:0:4567::3d:ff", 90));
assertTrue(thrown.getMessage().contains("If you config ip expression that contains '*'"));
thrown = assertThrows(
IllegalArgumentException.class,
() -> NetUtils.matchIpRange("234e:0:4567:3d", "234e:0:4567::3d:ff", 90));
assertTrue(thrown.getMessage().contains("The host is ipv6, but the pattern is not ipv6 pattern"));
thrown = assertThrows(
IllegalArgumentException.class, () -> NetUtils.matchIpRange("192.168.1.1-65-3", "192.168.1.63", 90));
assertTrue(thrown.getMessage().contains("There is wrong format of ip Address"));
}
@Test
void testMatchIpRangeMatchWhenIpWrongException() {
UnknownHostException thrown = assertThrows(
UnknownHostException.class, () -> NetUtils.matchIpRange("192.168.1.63", "192.168.1.ff", 90));
assertTrue(thrown.getMessage().contains("192.168.1.ff"));
}
@Test
void testMatchIpMatch() throws UnknownHostException {
assertTrue(NetUtils.matchIpExpression("192.168.1.*", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpExpression("192.168.1.192/26", "192.168.1.199", 90));
}
@Test
void testMatchIpv6WithIpPort() throws UnknownHostException {
assertTrue(NetUtils.matchIpRange("[234e:0:4567::3d:ee]", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee]", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee]:8090", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:0-ee]:8090", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee-ff]:8090", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:*]:90", "234e:0:4567::3d:ff", 90));
assertFalse(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee]:7289", "234e:0:4567::3d:ee", 8090));
assertFalse(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee-ff]:8090", "234e:0:4567::3d:ee", 9090));
}
@Test
void testMatchIpv4WithIpPort() throws UnknownHostException {
NumberFormatException thrown = assertThrows(
NumberFormatException.class,
() -> NetUtils.matchIpExpression("192.168.1.192/26:90", "192.168.1.199", 90));
assertTrue(thrown instanceof NumberFormatException);
assertTrue(NetUtils.matchIpRange("*.*.*.*:90", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.*:90", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.63:90", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.63-65:90", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpRange("192.168.1.1-63:90", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("*.*.*.*:80", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.*:80", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.63:80", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.63-65:80", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.1-63:80", "192.168.1.63", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.1-61:90", "192.168.1.62", 90));
assertFalse(NetUtils.matchIpRange("192.168.1.62:90", "192.168.1.63", 90));
}
@Test
void testLocalHost() {
assertEquals(NetUtils.getLocalHost(), NetUtils.getLocalAddress().getHostAddress());
assertTrue(NetUtils.isValidLocalHost(NetUtils.getLocalHost()));
assertFalse(NetUtils.isInvalidLocalHost(NetUtils.getLocalHost()));
}
@Test
void testIsMulticastAddress() {
assertTrue(NetUtils.isMulticastAddress("224.0.0.1"));
assertFalse(NetUtils.isMulticastAddress("127.0.0.1"));
}
@Test
void testFindNetworkInterface() {
assertNotNull(NetUtils.findNetworkInterface());
}
@Test
void testIgnoreAllInterfaces() {
// store the origin ignored interfaces
String originIgnoredInterfaces = this.getIgnoredInterfaces();
try {
// ignore all interfaces
this.setIgnoredInterfaces(".*");
assertNull(NetUtils.findNetworkInterface());
} finally {
// recover the origin ignored interfaces
this.setIgnoredInterfaces(originIgnoredInterfaces);
}
}
@Test
void testIgnoreGivenInterface() {
// store the origin ignored interfaces
String originIgnoredInterfaces = this.getIgnoredInterfaces();
try {
NetworkInterface networkInterface = NetUtils.findNetworkInterface();
assertNotNull(networkInterface);
// ignore the given network interface's display name
this.setIgnoredInterfaces(Pattern.quote(networkInterface.getDisplayName()));
NetworkInterface newNetworkInterface = NetUtils.findNetworkInterface();
if (newNetworkInterface != null) {
assertTrue(!networkInterface.getDisplayName().equals(newNetworkInterface.getDisplayName()));
}
} finally {
// recover the origin ignored interfaces
this.setIgnoredInterfaces(originIgnoredInterfaces);
}
}
@Test
void testIgnoreGivenPrefixInterfaceName() {
// store the origin ignored interfaces
String originIgnoredInterfaces = this.getIgnoredInterfaces();
try {
NetworkInterface networkInterface = NetUtils.findNetworkInterface();
assertNotNull(networkInterface);
// ignore the given prefix network interface's display name
String displayName = networkInterface.getDisplayName();
if (StringUtils.isNotEmpty(displayName) && displayName.length() > 2) {
String ignoredInterfaces = Pattern.quote(displayName.substring(0, 1)) + ".*";
this.setIgnoredInterfaces(ignoredInterfaces);
NetworkInterface newNetworkInterface = NetUtils.findNetworkInterface();
if (newNetworkInterface != null) {
assertTrue(!newNetworkInterface.getDisplayName().startsWith(displayName.substring(0, 1)));
}
}
} finally {
// recover the origin ignored interfaces
this.setIgnoredInterfaces(originIgnoredInterfaces);
}
}
private String getIgnoredInterfaces() {
return System.getProperty(DUBBO_NETWORK_IGNORED_INTERFACE);
}
private void setIgnoredInterfaces(String ignoredInterfaces) {
if (ignoredInterfaces != null) {
System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, ignoredInterfaces);
} else {
System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, "");
}
}
}
| 6,462 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ConcurrentHashMapUtilsTest {
@Test
public void testComputeIfAbsent() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
String ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm");
assertEquals("mxsm", ifAbsent);
ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm1");
assertEquals("mxsm", ifAbsent);
map.remove("mxsm");
ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm1");
assertEquals("mxsm1", ifAbsent);
}
@Test
@EnabledForJreRange(max = org.junit.jupiter.api.condition.JRE.JAVA_8)
public void issue11986ForJava8Test() {
// https://github.com/apache/dubbo/issues/11986
final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// // map.computeIfAbsent("AaAa", key->map.computeIfAbsent("BBBB",key2->42));
// In JDK8,for the bug of JDK-8161372,may cause dead cycle when use computeIfAbsent
// ConcurrentHashMapUtils.computeIfAbsent method to resolve this bug
ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
assertEquals(2, map.size());
assertEquals(Integer.valueOf(42), map.get("AaAa"));
assertEquals(Integer.valueOf(42), map.get("BBBB"));
}
@Test
@EnabledForJreRange(min = org.junit.jupiter.api.condition.JRE.JAVA_9)
public void issue11986ForJava17Test() {
// https://github.com/apache/dubbo/issues/11986
final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// JDK9+ has been resolved JDK-8161372 bug, when cause dead then throw IllegalStateException
assertThrows(IllegalStateException.class, () -> {
ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
});
}
}
| 6,463 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SerializeSecurityManagerTest {
@Test
void testPrefix() {
TestAllowClassNotifyListener.setCount(0);
SerializeSecurityManager ssm = new SerializeSecurityManager();
ssm.registerListener(new TestAllowClassNotifyListener());
ssm.addToAllowed("java.util.HashMap");
ssm.addToAllowed("com.example.DemoInterface");
ssm.addToAllowed("com.sun.Interface1");
ssm.addToAllowed("com.sun.Interface2");
Assertions.assertTrue(ssm.getAllowedPrefix().contains("java.util.HashMap"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.example.DemoInterface"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface2"));
Assertions.assertEquals(ssm.getAllowedPrefix(), TestAllowClassNotifyListener.getAllowedList());
Assertions.assertEquals(7, TestAllowClassNotifyListener.getCount());
ssm.addToDisAllowed("com.sun.Interface");
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface1"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface2"));
Assertions.assertEquals(ssm.getDisAllowedPrefix(), TestAllowClassNotifyListener.getDisAllowedList());
Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount());
ssm.addToAllowed("com.sun.Interface3");
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface3"));
Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount());
ssm.addToAllowed("java.util.HashMap");
Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount());
ssm.addToDisAllowed("com.sun.Interface");
Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount());
ssm.addToAlwaysAllowed("com.sun.Interface3");
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface3"));
Assertions.assertEquals(10, TestAllowClassNotifyListener.getCount());
ssm.addToAlwaysAllowed("com.sun.Interface3");
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface3"));
Assertions.assertEquals(10, TestAllowClassNotifyListener.getCount());
}
@Test
void testStatus1() {
SerializeSecurityManager ssm = new SerializeSecurityManager();
ssm.registerListener(new TestAllowClassNotifyListener());
Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, ssm.getCheckStatus());
Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.STRICT, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.WARN);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.WARN, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.WARN, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.DISABLE);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus());
ssm.setCheckStatus(SerializeCheckStatus.WARN);
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus());
}
@Test
void testStatus2() {
SerializeSecurityManager ssm = new SerializeSecurityManager();
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
ssm.registerListener(new TestAllowClassNotifyListener());
Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus());
Assertions.assertEquals(SerializeCheckStatus.STRICT, TestAllowClassNotifyListener.getStatus());
}
@Test
void testSerializable() {
SerializeSecurityManager ssm = new SerializeSecurityManager();
ssm.registerListener(new TestAllowClassNotifyListener());
Assertions.assertTrue(ssm.isCheckSerializable());
Assertions.assertTrue(TestAllowClassNotifyListener.isCheckSerializable());
ssm.setCheckSerializable(true);
Assertions.assertTrue(ssm.isCheckSerializable());
Assertions.assertTrue(TestAllowClassNotifyListener.isCheckSerializable());
ssm.setCheckSerializable(false);
Assertions.assertFalse(ssm.isCheckSerializable());
Assertions.assertFalse(TestAllowClassNotifyListener.isCheckSerializable());
ssm.setCheckSerializable(true);
Assertions.assertFalse(ssm.isCheckSerializable());
Assertions.assertFalse(TestAllowClassNotifyListener.isCheckSerializable());
}
}
| 6,464 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
/**
* {@link DefaultPage}
*
* @since 2.7.5
*/
class DefaultPageTest {
@Test
void test() {
List<Integer> data = asList(1, 2, 3, 4, 5);
DefaultPage<Integer> page = new DefaultPage<>(0, 1, data.subList(0, 1), data.size());
Assertions.assertEquals(page.getOffset(), 0);
Assertions.assertEquals(page.getPageSize(), 1);
Assertions.assertEquals(page.getTotalSize(), data.size());
Assertions.assertEquals(page.getData(), data.subList(0, 1));
Assertions.assertEquals(page.getTotalPages(), 5);
Assertions.assertTrue(page.hasNext());
}
}
| 6,465 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ExecutorUtilTest {
@Test
void testIsTerminated() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(true);
assertThat(ExecutorUtil.isTerminated(executor), is(true));
Executor executor2 = Mockito.mock(Executor.class);
assertThat(ExecutorUtil.isTerminated(executor2), is(false));
}
@Test
void testGracefulShutdown1() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, true);
when(executor.awaitTermination(20, TimeUnit.MILLISECONDS)).thenReturn(false);
ExecutorUtil.gracefulShutdown(executor, 20);
verify(executor).shutdown();
verify(executor).shutdownNow();
}
@Test
void testGracefulShutdown2() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, false, false);
when(executor.awaitTermination(20, TimeUnit.MILLISECONDS)).thenReturn(false);
when(executor.awaitTermination(10, TimeUnit.MILLISECONDS)).thenReturn(false, true);
ExecutorUtil.gracefulShutdown(executor, 20);
await().untilAsserted(() -> verify(executor, times(2)).awaitTermination(10, TimeUnit.MILLISECONDS));
verify(executor, times(1)).shutdown();
verify(executor, times(3)).shutdownNow();
}
@Test
void testShutdownNow() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, true);
ExecutorUtil.shutdownNow(executor, 20);
verify(executor).shutdownNow();
verify(executor).awaitTermination(20, TimeUnit.MILLISECONDS);
}
@Test
void testSetThreadName() throws Exception {
URL url = new ServiceConfigURL("dubbo", "localhost", 1234).addParameter(THREAD_NAME_KEY, "custom-thread");
url = ExecutorUtil.setThreadName(url, "default-name");
assertThat(url.getParameter(THREAD_NAME_KEY), equalTo("custom-thread-localhost:1234"));
}
}
| 6,466 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.MemberUtils.isPrivate;
import static org.apache.dubbo.common.utils.MemberUtils.isPublic;
import static org.apache.dubbo.common.utils.MemberUtils.isStatic;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link MemberUtils} Test
*
* @since 2.7.6
*/
class MemberUtilsTest {
@Test
void test() throws NoSuchMethodException {
assertFalse(isStatic(getClass().getMethod("noStatic")));
assertTrue(isStatic(getClass().getMethod("staticMethod")));
assertTrue(isPrivate(getClass().getDeclaredMethod("privateMethod")));
assertTrue(isPublic(getClass().getMethod("publicMethod")));
}
public void noStatic() {}
public static void staticMethod() {}
private void privateMethod() {}
public void publicMethod() {}
}
| 6,467 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.json.impl.FastJson2Impl;
import org.apache.dubbo.common.json.impl.FastJsonImpl;
import org.apache.dubbo.common.json.impl.GsonImpl;
import org.apache.dubbo.common.json.impl.JacksonImpl;
import org.apache.dubbo.common.utils.json.TestEnum;
import org.apache.dubbo.common.utils.json.TestObjectA;
import org.apache.dubbo.common.utils.json.TestObjectB;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class JsonUtilsTest {
private AtomicBoolean allowFastjson2 = new AtomicBoolean(true);
private AtomicBoolean allowFastjson = new AtomicBoolean(true);
private AtomicBoolean allowGson = new AtomicBoolean(true);
private AtomicBoolean allowJackson = new AtomicBoolean(true);
private MockedConstruction<FastJson2Impl> fastjson2Mock;
private MockedConstruction<FastJsonImpl> fastjsonMock;
private MockedConstruction<GsonImpl> gsonMock;
private MockedConstruction<JacksonImpl> jacksonMock;
@AfterEach
void teardown() {
if (fastjsonMock != null) {
fastjsonMock.close();
}
if (fastjson2Mock != null) {
fastjson2Mock.close();
}
if (gsonMock != null) {
gsonMock.close();
}
if (jacksonMock != null) {
jacksonMock.close();
}
}
@Test
void testGetJson1() {
Assertions.assertNotNull(JsonUtils.getJson());
Assertions.assertEquals(JsonUtils.getJson(), JsonUtils.getJson());
Map<String, String> map = new HashMap<>();
map.put("a", "a");
Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map));
Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class));
Assertions.assertEquals(
Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class));
// prefer use fastjson2
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson2");
Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map));
Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class));
Assertions.assertEquals(
Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class));
System.clearProperty("dubbo.json-framework.prefer");
// prefer use fastjson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson");
Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map));
Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class));
Assertions.assertEquals(
Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class));
System.clearProperty("dubbo.json-framework.prefer");
// prefer use gson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "gson");
Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map));
Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class));
Assertions.assertEquals(
Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class));
System.clearProperty("dubbo.json-framework.prefer");
// prefer use jackson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "jackson");
Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map));
Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class));
Assertions.assertEquals(
Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class));
System.clearProperty("dubbo.json-framework.prefer");
JsonUtils.setJson(null);
}
@Test
void consistentTest() {
List<Object> objs = new LinkedList<>();
{
objs.add(null);
}
{
Map<String, String> map = new HashMap<>();
map.put("a", "a");
objs.add(map);
}
{
TestObjectA a = new TestObjectA();
objs.add(a);
}
{
TestObjectA a = new TestObjectA();
a.setTestEnum(TestEnum.TYPE_A);
objs.add(a);
}
{
TestObjectB b = new TestObjectB();
objs.add(b);
}
{
TestObjectB b = new TestObjectB();
b.setInnerA(new TestObjectB.Inner());
b.setInnerB(new TestObjectB.Inner());
objs.add(b);
}
{
TestObjectB b = new TestObjectB();
TestObjectB.Inner inner1 = new TestObjectB.Inner();
TestObjectB.Inner inner2 = new TestObjectB.Inner();
inner1.setName("Test");
inner2.setName("Test");
b.setInnerA(inner1);
b.setInnerB(inner2);
objs.add(b);
}
{
TestObjectB b = new TestObjectB();
TestObjectB.Inner inner1 = new TestObjectB.Inner();
inner1.setName("Test");
b.setInnerA(inner1);
b.setInnerB(inner1);
objs.add(b);
}
for (Object obj : objs) {
// prefer use fastjson2
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson2");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
String fromFastjson2 = JsonUtils.getJson().toJson(obj);
System.clearProperty("dubbo.json-framework.prefer");
// prefer use fastjson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson");
Assertions.assertInstanceOf(FastJsonImpl.class, JsonUtils.getJson());
String fromFastjson1 = JsonUtils.getJson().toJson(obj);
System.clearProperty("dubbo.json-framework.prefer");
// prefer use gson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "gson");
Assertions.assertInstanceOf(GsonImpl.class, JsonUtils.getJson());
String fromGson = JsonUtils.getJson().toJson(obj);
System.clearProperty("dubbo.json-framework.prefer");
// prefer use jackson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "jackson");
Assertions.assertInstanceOf(JacksonImpl.class, JsonUtils.getJson());
String fromJackson = JsonUtils.getJson().toJson(obj);
System.clearProperty("dubbo.json-framework.prefer");
JsonUtils.setJson(null);
Assertions.assertEquals(fromFastjson1, fromFastjson2);
Assertions.assertEquals(fromFastjson1, fromGson);
Assertions.assertEquals(fromFastjson2, fromGson);
Assertions.assertEquals(fromFastjson1, fromJackson);
Assertions.assertEquals(fromFastjson2, fromJackson);
}
}
@Test
void testGetJson2() {
fastjson2Mock = Mockito.mockConstruction(FastJson2Impl.class, (mock, context) -> Mockito.when(mock.isSupport())
.thenAnswer(invocation -> allowFastjson2.get()));
fastjsonMock = Mockito.mockConstruction(FastJsonImpl.class, (mock, context) -> Mockito.when(mock.isSupport())
.thenAnswer(invocation -> allowFastjson.get()));
gsonMock = Mockito.mockConstruction(GsonImpl.class, (mock, context) -> Mockito.when(mock.isSupport())
.thenAnswer(invocation -> allowGson.get()));
jacksonMock = Mockito.mockConstruction(JacksonImpl.class, (mock, context) -> Mockito.when(mock.isSupport())
.thenAnswer(invocation -> allowJackson.get()));
// default use fastjson2
JsonUtils.setJson(null);
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
// prefer use fastjson2
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson2");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
// prefer use fastjson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "fastjson");
Assertions.assertInstanceOf(FastJsonImpl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
// prefer use gson
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "gson");
Assertions.assertInstanceOf(GsonImpl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
// prefer use not found
JsonUtils.setJson(null);
System.setProperty("dubbo.json-framework.prefer", "notfound");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
JsonUtils.setJson(null);
// TCCL not found fastjson2
allowFastjson2.set(false);
Assertions.assertInstanceOf(FastJsonImpl.class, JsonUtils.getJson());
allowFastjson2.set(true);
JsonUtils.setJson(null);
// TCCL not found fastjson2, fastjson
allowFastjson2.set(false);
allowFastjson.set(false);
Assertions.assertInstanceOf(GsonImpl.class, JsonUtils.getJson());
allowFastjson.set(true);
allowFastjson2.set(true);
JsonUtils.setJson(null);
// TCCL not found fastjson2, fastjson, gson
allowFastjson2.set(false);
allowFastjson.set(false);
allowGson.set(false);
Assertions.assertInstanceOf(JacksonImpl.class, JsonUtils.getJson());
allowGson.set(true);
allowFastjson.set(true);
allowFastjson2.set(true);
JsonUtils.setJson(null);
// TCCL not found fastjson2, prefer use fastjson2
allowFastjson2.set(false);
System.setProperty("dubbo.json-framework.prefer", "fastjson2");
Assertions.assertInstanceOf(FastJsonImpl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
allowFastjson2.set(true);
JsonUtils.setJson(null);
// TCCL not found fastjson, prefer use fastjson
allowFastjson.set(false);
System.setProperty("dubbo.json-framework.prefer", "fastjson");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
allowFastjson.set(true);
JsonUtils.setJson(null);
// TCCL not found gson, prefer use gson
allowGson.set(false);
System.setProperty("dubbo.json-framework.prefer", "gson");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
allowGson.set(true);
JsonUtils.setJson(null);
// TCCL not found jackson, prefer use jackson
allowJackson.set(false);
System.setProperty("dubbo.json-framework.prefer", "jackson");
Assertions.assertInstanceOf(FastJson2Impl.class, JsonUtils.getJson());
System.clearProperty("dubbo.json-framework.prefer");
allowJackson.set(true);
JsonUtils.setJson(null);
// TCCL not found fastjson, gson
allowFastjson2.set(false);
allowFastjson.set(false);
allowGson.set(false);
allowJackson.set(false);
Assertions.assertThrows(IllegalStateException.class, JsonUtils::getJson);
allowGson.set(true);
allowFastjson.set(true);
allowFastjson2.set(true);
allowJackson.set(true);
JsonUtils.setJson(null);
}
}
| 6,468 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
class AtomicPositiveIntegerTest {
private AtomicPositiveInteger i1 = new AtomicPositiveInteger();
private AtomicPositiveInteger i2 = new AtomicPositiveInteger(127);
private AtomicPositiveInteger i3 = new AtomicPositiveInteger(Integer.MAX_VALUE);
@Test
void testGet() {
assertEquals(0, i1.get());
assertEquals(127, i2.get());
assertEquals(Integer.MAX_VALUE, i3.get());
}
@Test
void testSet() {
i1.set(100);
assertEquals(100, i1.get());
try {
i1.set(-1);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0")));
}
}
@Test
void testGetAndIncrement() {
int get = i1.getAndIncrement();
assertEquals(0, get);
assertEquals(1, i1.get());
get = i2.getAndIncrement();
assertEquals(127, get);
assertEquals(128, i2.get());
get = i3.getAndIncrement();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(0, i3.get());
}
@Test
void testGetAndDecrement() {
int get = i1.getAndDecrement();
assertEquals(0, get);
assertEquals(Integer.MAX_VALUE, i1.get());
get = i2.getAndDecrement();
assertEquals(127, get);
assertEquals(126, i2.get());
get = i3.getAndDecrement();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(Integer.MAX_VALUE - 1, i3.get());
}
@Test
void testIncrementAndGet() {
int get = i1.incrementAndGet();
assertEquals(1, get);
assertEquals(1, i1.get());
get = i2.incrementAndGet();
assertEquals(128, get);
assertEquals(128, i2.get());
get = i3.incrementAndGet();
assertEquals(0, get);
assertEquals(0, i3.get());
}
@Test
void testDecrementAndGet() {
int get = i1.decrementAndGet();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(Integer.MAX_VALUE, i1.get());
get = i2.decrementAndGet();
assertEquals(126, get);
assertEquals(126, i2.get());
get = i3.decrementAndGet();
assertEquals(Integer.MAX_VALUE - 1, get);
assertEquals(Integer.MAX_VALUE - 1, i3.get());
}
@Test
void testGetAndSet() {
int get = i1.getAndSet(100);
assertEquals(0, get);
assertEquals(100, i1.get());
try {
i1.getAndSet(-1);
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0")));
}
}
@Test
void testGetAndAnd() {
int get = i1.getAndAdd(3);
assertEquals(0, get);
assertEquals(3, i1.get());
get = i2.getAndAdd(3);
assertEquals(127, get);
assertEquals(127 + 3, i2.get());
get = i3.getAndAdd(3);
assertEquals(Integer.MAX_VALUE, get);
assertEquals(2, i3.get());
}
@Test
void testAddAndGet() {
int get = i1.addAndGet(3);
assertEquals(3, get);
assertEquals(3, i1.get());
get = i2.addAndGet(3);
assertEquals(127 + 3, get);
assertEquals(127 + 3, i2.get());
get = i3.addAndGet(3);
assertEquals(2, get);
assertEquals(2, i3.get());
}
@Test
void testCompareAndSet1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
i1.compareAndSet(i1.get(), -1);
});
}
@Test
void testCompareAndSet2() {
assertThat(i1.compareAndSet(i1.get(), 2), is(true));
assertThat(i1.get(), is(2));
}
@Test
void testWeakCompareAndSet1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
i1.weakCompareAndSet(i1.get(), -1);
});
}
@Test
void testWeakCompareAndSet2() {
assertThat(i1.weakCompareAndSet(i1.get(), 2), is(true));
assertThat(i1.get(), is(2));
}
@Test
void testValues() {
Integer i = i1.get();
assertThat(i1.byteValue(), equalTo(i.byteValue()));
assertThat(i1.shortValue(), equalTo(i.shortValue()));
assertThat(i1.intValue(), equalTo(i.intValue()));
assertThat(i1.longValue(), equalTo(i.longValue()));
assertThat(i1.floatValue(), equalTo(i.floatValue()));
assertThat(i1.doubleValue(), equalTo(i.doubleValue()));
assertThat(i1.toString(), equalTo(i.toString()));
}
@Test
void testEquals() {
assertEquals(new AtomicPositiveInteger(), new AtomicPositiveInteger());
assertEquals(new AtomicPositiveInteger(1), new AtomicPositiveInteger(1));
}
}
| 6,469 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.MethodUtils.excludedDeclaredClass;
import static org.apache.dubbo.common.utils.MethodUtils.findMethod;
import static org.apache.dubbo.common.utils.MethodUtils.findNearestOverriddenMethod;
import static org.apache.dubbo.common.utils.MethodUtils.findOverriddenMethod;
import static org.apache.dubbo.common.utils.MethodUtils.getAllDeclaredMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getAllMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getDeclaredMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getMethods;
import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod;
import static org.apache.dubbo.common.utils.MethodUtils.overrides;
class MethodUtilsTest {
@Test
void testGetMethod() {
Method getMethod = null;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isGetter(method)) {
getMethod = method;
}
}
Assertions.assertNotNull(getMethod);
Assertions.assertEquals("getValue", getMethod.getName());
}
@Test
void testSetMethod() {
Method setMethod = null;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isSetter(method)) {
setMethod = method;
}
}
Assertions.assertNotNull(setMethod);
Assertions.assertEquals("setValue", setMethod.getName());
}
@Test
void testIsDeprecated() throws Exception {
Assertions.assertTrue(MethodUtils.isDeprecated(MethodTestClazz.class.getMethod("deprecatedMethod")));
Assertions.assertFalse(MethodUtils.isDeprecated(MethodTestClazz.class.getMethod("getValue")));
}
@Test
void testIsMetaMethod() {
boolean containMetaMethod = false;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isMetaMethod(method)) {
containMetaMethod = true;
}
}
Assertions.assertTrue(containMetaMethod);
}
@Test
void testGetMethods() throws NoSuchMethodException {
Assertions.assertTrue(getDeclaredMethods(MethodTestClazz.class, excludedDeclaredClass(String.class))
.size()
> 0);
Assertions.assertTrue(getMethods(MethodTestClazz.class).size() > 0);
Assertions.assertTrue(getAllDeclaredMethods(MethodTestClazz.class).size() > 0);
Assertions.assertTrue(getAllMethods(MethodTestClazz.class).size() > 0);
Assertions.assertNotNull(findMethod(MethodTestClazz.class, "getValue"));
MethodTestClazz methodTestClazz = new MethodTestClazz();
invokeMethod(methodTestClazz, "setValue", "Test");
Assertions.assertEquals(methodTestClazz.getValue(), "Test");
Assertions.assertTrue(
overrides(MethodOverrideClazz.class.getMethod("get"), MethodTestClazz.class.getMethod("get")));
Assertions.assertEquals(
findNearestOverriddenMethod(MethodOverrideClazz.class.getMethod("get")),
MethodTestClazz.class.getMethod("get"));
Assertions.assertEquals(
findOverriddenMethod(MethodOverrideClazz.class.getMethod("get"), MethodOverrideClazz.class),
MethodTestClazz.class.getMethod("get"));
}
@Test
void testExtractFieldName() throws Exception {
Method m1 = MethodFieldTestClazz.class.getMethod("is");
Method m2 = MethodFieldTestClazz.class.getMethod("get");
Method m3 = MethodFieldTestClazz.class.getMethod("getClass");
Method m4 = MethodFieldTestClazz.class.getMethod("getObject");
Method m5 = MethodFieldTestClazz.class.getMethod("getFieldName1");
Method m6 = MethodFieldTestClazz.class.getMethod("setFieldName2");
Method m7 = MethodFieldTestClazz.class.getMethod("isFieldName3");
Assertions.assertEquals("", MethodUtils.extractFieldName(m1));
Assertions.assertEquals("", MethodUtils.extractFieldName(m2));
Assertions.assertEquals("", MethodUtils.extractFieldName(m3));
Assertions.assertEquals("", MethodUtils.extractFieldName(m4));
Assertions.assertEquals("fieldName1", MethodUtils.extractFieldName(m5));
Assertions.assertEquals("fieldName2", MethodUtils.extractFieldName(m6));
Assertions.assertEquals("fieldName3", MethodUtils.extractFieldName(m7));
}
public class MethodFieldTestClazz {
public String is() {
return "";
}
public String get() {
return "";
}
public String getObject() {
return "";
}
public String getFieldName1() {
return "";
}
public String setFieldName2() {
return "";
}
public String isFieldName3() {
return "";
}
}
public class MethodTestClazz {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public MethodTestClazz get() {
return this;
}
@Deprecated
public Boolean deprecatedMethod() {
return true;
}
}
public class MethodOverrideClazz extends MethodTestClazz {
@Override
public MethodTestClazz get() {
return this;
}
}
}
| 6,470 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ParametersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ParametersTest {
final String ServiceName = "org.apache.dubbo.rpc.service.GenericService";
final String ServiceVersion = "1.0.15";
final String LoadBalance = "lcr";
public void testMap2Parameters() {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "org.apache.dubbo.rpc.service.GenericService");
map.put("version", "1.0.15");
map.put("lb", "lcr");
map.put("max.active", "500");
assertEquals(map.get("name"), ServiceName);
assertEquals(map.get("version"), ServiceVersion);
assertEquals(map.get("lb"), LoadBalance);
}
public void testString2Parameters() throws Exception {
String qs = "name=org.apache.dubbo.rpc.service.GenericService&version=1.0.15&lb=lcr";
Map<String, String> map = StringUtils.parseQueryString(qs);
assertEquals(map.get("name"), ServiceName);
assertEquals(map.get("version"), ServiceVersion);
assertEquals(map.get("lb"), LoadBalance);
}
}
| 6,471 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsInterfaceDisplayNameHasMetaCharactersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_NETWORK_IGNORED_INTERFACE;
import static org.junit.jupiter.api.Assertions.assertTrue;
class NetUtilsInterfaceDisplayNameHasMetaCharactersTest {
private static final String IGNORED_DISPLAY_NAME_HAS_METACHARACTERS = "Mock(R) ^$*+[?].|-[0-9] Adapter";
private static final String SELECTED_DISPLAY_NAME = "Selected Adapter";
private static final String SELECTED_HOST_ADDR = "192.168.0.1";
@Test
void testIgnoreGivenInterfaceNameWithMetaCharacters() throws Exception {
String originIgnoredInterfaces = this.getIgnoredInterfaces();
// mock static methods of final class NetworkInterface
try (MockedStatic<NetworkInterface> mockedStaticNetif = Mockito.mockStatic(NetworkInterface.class)) {
NetworkInterface mockIgnoredNetif = Mockito.mock(NetworkInterface.class);
NetworkInterface mockSelectedNetif = Mockito.mock(NetworkInterface.class);
NetworkInterface[] mockNetifs = {mockIgnoredNetif, mockSelectedNetif};
Enumeration<NetworkInterface> mockEnumIfs = new Enumeration<NetworkInterface>() {
private int i = 0;
public NetworkInterface nextElement() {
if (mockNetifs != null && i < mockNetifs.length) {
NetworkInterface netif = mockNetifs[i++];
return netif;
} else {
throw new NoSuchElementException();
}
}
public boolean hasMoreElements() {
return (mockNetifs != null && i < mockNetifs.length);
}
};
InetAddress mockSelectedAddr = Mockito.mock(InetAddress.class);
InetAddress[] mockAddrs = {mockSelectedAddr};
Enumeration<InetAddress> mockEnumAddrs = new Enumeration<InetAddress>() {
private int i = 0;
public InetAddress nextElement() {
if (mockAddrs != null && i < mockAddrs.length) {
InetAddress addr = mockAddrs[i++];
return addr;
} else {
throw new NoSuchElementException();
}
}
public boolean hasMoreElements() {
return (mockAddrs != null && i < mockAddrs.length);
}
};
// mock static method getNetworkInterfaces
mockedStaticNetif
.when(() -> {
NetworkInterface.getNetworkInterfaces();
})
.thenReturn(mockEnumIfs);
Mockito.when(mockIgnoredNetif.isUp()).thenReturn(true);
Mockito.when(mockIgnoredNetif.getDisplayName()).thenReturn(IGNORED_DISPLAY_NAME_HAS_METACHARACTERS);
Mockito.when(mockSelectedNetif.isUp()).thenReturn(true);
Mockito.when(mockSelectedNetif.getDisplayName()).thenReturn(SELECTED_DISPLAY_NAME);
Mockito.when(mockSelectedNetif.getInetAddresses()).thenReturn(mockEnumAddrs);
Mockito.when(mockSelectedAddr.isLoopbackAddress()).thenReturn(false);
Mockito.when(mockSelectedAddr.getHostAddress()).thenReturn(SELECTED_HOST_ADDR);
Mockito.when(mockSelectedAddr.isReachable(Mockito.anyInt())).thenReturn(true);
this.setIgnoredInterfaces(IGNORED_DISPLAY_NAME_HAS_METACHARACTERS);
NetworkInterface newNetworkInterface = NetUtils.findNetworkInterface();
assertTrue(!IGNORED_DISPLAY_NAME_HAS_METACHARACTERS.equals(newNetworkInterface.getDisplayName()));
} finally {
// recover the origin ignored interfaces
this.setIgnoredInterfaces(originIgnoredInterfaces);
}
}
private String getIgnoredInterfaces() {
return System.getProperty(DUBBO_NETWORK_IGNORED_INTERFACE);
}
private void setIgnoredInterfaces(String ignoredInterfaces) {
if (ignoredInterfaces != null) {
System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, ignoredInterfaces);
} else {
System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, "");
}
}
}
| 6,472 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.config.ProtocolConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
import static org.apache.dubbo.common.utils.CollectionUtils.toMap;
import static org.apache.dubbo.common.utils.CollectionUtils.toStringMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CollectionUtilsTest {
@Test
void testSort() {
List<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(10);
list.add(20);
List<Integer> expected = new ArrayList<Integer>();
expected.add(10);
expected.add(20);
expected.add(100);
assertEquals(expected, CollectionUtils.sort(list));
}
@Test
void testSortNull() {
assertNull(CollectionUtils.sort(null));
assertTrue(CollectionUtils.sort(new ArrayList<Integer>()).isEmpty());
}
@Test
void testSortSimpleName() {
List<String> list = new ArrayList<String>();
list.add("aaa.z");
list.add("b");
list.add(null);
list.add("zzz.a");
list.add("c");
list.add(null);
List<String> sorted = CollectionUtils.sortSimpleName(list);
assertNull(sorted.get(0));
assertNull(sorted.get(1));
}
@Test
void testSortSimpleNameNull() {
assertNull(CollectionUtils.sortSimpleName(null));
assertTrue(CollectionUtils.sortSimpleName(new ArrayList<String>()).isEmpty());
}
@Test
void testFlip() {
assertEquals(CollectionUtils.flip(null), null);
Map<String, String> input1 = new HashMap<>();
input1.put("k1", null);
input1.put("k2", "v2");
Map<String, String> output1 = new HashMap<>();
output1.put(null, "k1");
output1.put("v2", "k2");
assertEquals(CollectionUtils.flip(input1), output1);
Map<String, String> input2 = new HashMap<>();
input2.put("k1", null);
input2.put("k2", null);
assertThrows(IllegalArgumentException.class, () -> CollectionUtils.flip(input2));
}
@Test
void testSplitAll() {
assertNull(CollectionUtils.splitAll(null, null));
assertNull(CollectionUtils.splitAll(null, "-"));
assertTrue(CollectionUtils.splitAll(new HashMap<String, List<String>>(), "-")
.isEmpty());
Map<String, List<String>> input = new HashMap<String, List<String>>();
input.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
input.put("key2", Arrays.asList("1:a", "2:b"));
input.put("key3", null);
input.put("key4", new ArrayList<String>());
Map<String, Map<String, String>> expected = new HashMap<String, Map<String, String>>();
expected.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
expected.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
expected.put("key3", null);
expected.put("key4", new HashMap<String, String>());
assertEquals(expected, CollectionUtils.splitAll(input, ":"));
}
@Test
void testJoinAll() {
assertNull(CollectionUtils.joinAll(null, null));
assertNull(CollectionUtils.joinAll(null, "-"));
Map<String, List<String>> expected = new HashMap<String, List<String>>();
expected.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
expected.put("key2", Arrays.asList("1:a", "2:b"));
expected.put("key3", null);
expected.put("key4", new ArrayList<String>());
Map<String, Map<String, String>> input = new HashMap<String, Map<String, String>>();
input.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
input.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
input.put("key3", null);
input.put("key4", new HashMap<String, String>());
Map<String, List<String>> output = CollectionUtils.joinAll(input, ":");
for (Map.Entry<String, List<String>> entry : output.entrySet()) {
if (entry.getValue() == null) continue;
Collections.sort(entry.getValue());
}
assertEquals(expected, output);
}
@Test
void testJoinList() {
List<String> list = emptyList();
assertEquals("", CollectionUtils.join(list, "/"));
list = Arrays.asList("x");
assertEquals("x", CollectionUtils.join(list, "-"));
list = Arrays.asList("a", "b");
assertEquals("a/b", CollectionUtils.join(list, "/"));
}
@Test
void testMapEquals() {
assertTrue(CollectionUtils.mapEquals(null, null));
assertFalse(CollectionUtils.mapEquals(null, new HashMap<String, String>()));
assertFalse(CollectionUtils.mapEquals(new HashMap<String, String>(), null));
assertTrue(CollectionUtils.mapEquals(
CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b")));
assertFalse(CollectionUtils.mapEquals(
CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b")));
}
@Test
void testStringMap1() {
assertThat(toStringMap("key", "value"), equalTo(Collections.singletonMap("key", "value")));
}
@Test
void testStringMap2() {
Assertions.assertThrows(IllegalArgumentException.class, () -> toStringMap("key", "value", "odd"));
}
@Test
void testToMap1() {
assertTrue(CollectionUtils.toMap().isEmpty());
Map<String, Integer> expected = new HashMap<String, Integer>();
expected.put("a", 1);
expected.put("b", 2);
expected.put("c", 3);
assertEquals(expected, CollectionUtils.toMap("a", 1, "b", 2, "c", 3));
}
@Test
void testObjectToMap() throws Exception {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setSerialization("fastjson2");
assertFalse(CollectionUtils.objToMap(protocolConfig).isEmpty());
}
@Test
void testToMap2() {
Assertions.assertThrows(IllegalArgumentException.class, () -> toMap("a", "b", "c"));
}
@Test
void testIsEmpty() {
assertThat(isEmpty(null), is(true));
assertThat(isEmpty(new HashSet()), is(true));
assertThat(isEmpty(emptyList()), is(true));
}
@Test
void testIsNotEmpty() {
assertThat(isNotEmpty(singleton("a")), is(true));
}
@Test
void testOfSet() {
Set<String> set = ofSet();
assertEquals(emptySet(), set);
set = ofSet(((String[]) null));
assertEquals(emptySet(), set);
set = ofSet("A", "B", "C");
Set<String> expectedSet = new LinkedHashSet<>();
expectedSet.add("A");
expectedSet.add("B");
expectedSet.add("C");
assertEquals(expectedSet, set);
}
}
| 6,473 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
class JVMUtilTest {}
| 6,474 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import com.service.DemoService1;
import com.service.DemoService2;
import com.service.DemoService4;
import com.service.Params;
import com.service.Service;
import com.service.User;
import com.service.UserService;
import com.service.deep1.deep2.deep3.DemoService3;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST;
import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST;
class SerializeSecurityConfiguratorTest {
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("java.util.HashMap"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.example.DemoInterface"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface1"));
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("com.exampletest.DemoInterface"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface2"));
Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.DISABLE.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.WARN.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.WARN, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.STRICT.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus4() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CommonConstants.CLASS_DESERIALIZE_OPEN_CHECK, "false");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus());
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_OPEN_CHECK);
frameworkModel.destroy();
}
@Test
void testStatus5() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL, "true");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus());
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testConfig1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2"));
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST);
frameworkModel.destroy();
}
@Test
void testConfig2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CLASS_DESERIALIZE_BLOCKED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package2"));
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testConfig3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.package2, ,");
System.setProperty(CLASS_DESERIALIZE_BLOCKED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2"));
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST);
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testSerializable1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setCheckSerializable(false);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertFalse(ssm.isCheckSerializable());
frameworkModel.destroy();
}
@Test
void testSerializable2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.isCheckSerializable());
frameworkModel.destroy();
}
@Test
void testGeneric() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService4.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService4"));
frameworkModel.destroy();
}
@Test
void testGenericClass() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(UserService.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains(UserService.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Service.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Params.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(User.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService1.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(List.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Set.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Map.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(LinkedList.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Vector.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(HashSet.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService2.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(List.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Set.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Map.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(LinkedList.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Vector.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(HashSet.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setAutoTrustSerializeClass(false);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService1.class);
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.service.DemoService1"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
frameworkModel.destroy();
}
@Test
void testRegister4() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setTrustSerializeClassLevel(4);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService3.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2."));
frameworkModel.destroy();
}
@Test
void testRegister5() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setTrustSerializeClassLevel(10);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService3.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2.deep3.DemoService3"));
frameworkModel.destroy();
}
}
| 6,475 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/RegexPropertiesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class RegexPropertiesTest {
@Test
void testGetProperty() {
RegexProperties regexProperties = new RegexProperties();
regexProperties.setProperty("org.apache.dubbo.provider.*", "http://localhost:20880");
regexProperties.setProperty("org.apache.dubbo.provider.config.*", "http://localhost:30880");
regexProperties.setProperty("org.apache.dubbo.provider.config.demo", "http://localhost:40880");
regexProperties.setProperty("org.apache.dubbo.consumer.*.demo", "http://localhost:50880");
regexProperties.setProperty("*.service", "http://localhost:60880");
Assertions.assertEquals(
"http://localhost:20880", regexProperties.getProperty("org.apache.dubbo.provider.cluster"));
Assertions.assertEquals(
"http://localhost:30880", regexProperties.getProperty("org.apache.dubbo.provider.config.cluster"));
Assertions.assertEquals(
"http://localhost:40880", regexProperties.getProperty("org.apache.dubbo.provider.config.demo"));
Assertions.assertEquals(
"http://localhost:50880", regexProperties.getProperty("org.apache.dubbo.consumer.service.demo"));
Assertions.assertEquals("http://localhost:60880", regexProperties.getProperty("org.apache.dubbo.service"));
}
}
| 6,476 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultCharSequence.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.lang.Prioritized;
/**
* Default {@link CharSequence}
*
* @since 2.7.5
*/
public class DefaultCharSequence implements CharSequence, Prioritized {
@Override
public int length() {
return 0;
}
@Override
public char charAt(int index) {
return 0;
}
@Override
public CharSequence subSequence(int start, int end) {
return null;
}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
}
| 6,477 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.log4j.Level;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LogUtilTest {
@AfterEach
public void tearDown() throws Exception {
DubboAppender.logList.clear();
}
@Test
void testStartStop() {
LogUtil.start();
assertThat(DubboAppender.available, is(true));
LogUtil.stop();
assertThat(DubboAppender.available, is(false));
}
@Test
void testCheckNoError() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
assertThat(LogUtil.checkNoError(), is(false));
when(log.getLogLevel()).thenReturn(Level.INFO);
assertThat(LogUtil.checkNoError(), is(true));
}
@Test
void testFindName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogName()).thenReturn("a");
assertThat(LogUtil.findName("a"), equalTo(1));
}
@Test
void testFindLevel() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
assertThat(LogUtil.findLevel(Level.ERROR), equalTo(1));
assertThat(LogUtil.findLevel(Level.INFO), equalTo(0));
}
@Test
void testFindLevelWithThreadName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
when(log.getLogThread()).thenReturn("thread-1");
log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
when(log.getLogThread()).thenReturn("thread-2");
assertThat(LogUtil.findLevelWithThreadName(Level.ERROR, "thread-2"), equalTo(1));
}
@Test
void testFindThread() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogThread()).thenReturn("thread-1");
assertThat(LogUtil.findThread("thread-1"), equalTo(1));
}
@Test
void testFindMessage1() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
assertThat(LogUtil.findMessage("message"), equalTo(1));
}
@Test
void testFindMessage2() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
when(log.getLogLevel()).thenReturn(Level.ERROR);
log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
when(log.getLogLevel()).thenReturn(Level.INFO);
assertThat(LogUtil.findMessage(Level.ERROR, "message"), equalTo(1));
}
}
| 6,478 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.URL;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
class UrlUtilsTest {
String localAddress = "127.0.0.1";
@Test
void testAddressNull() {
String exceptionMessage = "Address is not allowed to be empty, please re-enter.";
try {
UrlUtils.parseURL(null, null);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(exceptionMessage, illegalArgumentException.getMessage());
}
}
@Test
void testParseUrl() {
String address = "remote://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url = UrlUtils.parseURL(address, null);
assertEquals(localAddress + ":9090", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals("dubbo.test.api", url.getPath());
assertEquals(9090, url.getPort());
assertEquals("remote", url.getProtocol());
}
@Test
void testParseURLWithSpecial() {
String address = "127.0.0.1:2181?backup=127.0.0.1:2182,127.0.0.1:2183";
assertEquals("dubbo://" + address, UrlUtils.parseURL(address, null).toString());
}
@Test
void testDefaultUrl() {
String address = "127.0.0.1";
URL url = UrlUtils.parseURL(address, null);
assertEquals(localAddress + ":9090", url.getAddress());
assertEquals(9090, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertNull(url.getUsername());
assertNull(url.getPassword());
assertNull(url.getPath());
}
@Test
void testParseFromParameter() {
String address = "127.0.0.1";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
parameters.put("path", "dubbo.test.api");
parameters.put("aaa", "bbb");
parameters.put("ccc", "ddd");
URL url = UrlUtils.parseURL(address, parameters);
assertEquals(localAddress + ":10000", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals(10000, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertEquals("dubbo.test.api", url.getPath());
assertEquals("bbb", url.getParameter("aaa"));
assertEquals("ddd", url.getParameter("ccc"));
}
@Test
void testParseUrl2() {
String address = "192.168.0.1";
String backupAddress1 = "192.168.0.2";
String backupAddress2 = "192.168.0.3";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
URL url = UrlUtils.parseURL(address + "," + backupAddress1 + "," + backupAddress2, parameters);
assertEquals("192.168.0.1:10000", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals(10000, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertEquals("192.168.0.2" + "," + "192.168.0.3", url.getParameter("backup"));
}
@Test
void testParseUrls() {
String addresses = "192.168.0.1|192.168.0.2|192.168.0.3";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
List<URL> urls = UrlUtils.parseURLs(addresses, parameters);
assertEquals("192.168.0.1" + ":10000", urls.get(0).getAddress());
assertEquals("192.168.0.2" + ":10000", urls.get(1).getAddress());
}
@Test
void testParseUrlsAddressNull() {
String exceptionMessage = "Address is not allowed to be empty, please re-enter.";
try {
UrlUtils.parseURLs(null, null);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(exceptionMessage, illegalArgumentException.getMessage());
}
}
@Test
void testConvertRegister() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
register.put(key, null);
Map<String, Map<String, String>> newRegister = UrlUtils.convertRegister(register);
assertEquals(register, newRegister);
}
@Test
void testConvertRegister2() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "version=1.0.0&group=test&dubbo.version=2.0.0");
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.convertRegister(register);
Map<String, String> newService = new HashMap<String, String>();
newService.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "dubbo.version=2.0.0&group=test&version=1.0.0");
assertEquals(newService, newRegister.get("test/dubbo.test.api.HelloService:1.0.0"));
}
@Test
void testSubscribe() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe);
assertEquals(subscribe, newSubscribe);
}
@Test
void testSubscribe2() {
String key = "dubbo.test.api.HelloService";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, "version=1.0.0&group=test&dubbo.version=2.0.0");
Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe);
assertEquals(
"dubbo.version=2.0.0&group=test&version=1.0.0",
newSubscribe.get("test/dubbo.test.api.HelloService:1.0.0"));
}
@Test
void testRevertRegister() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertRegister(register);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("dubbo.test.api.HelloService", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertRegister2() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertRegister(register);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
expectedRegister.put("dubbo.test.api.HelloService", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertSubscribe() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.revertSubscribe(subscribe);
Map<String, String> expectSubscribe = new HashMap<String, String>();
expectSubscribe.put("dubbo.test.api.HelloService", "group=perf&version=1.0.0");
assertEquals(expectSubscribe, newSubscribe);
}
@Test
void testRevertSubscribe2() {
String key = "dubbo.test.api.HelloService";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.revertSubscribe(subscribe);
assertEquals(subscribe, newSubscribe);
}
@Test
void testRevertNotify() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> notify = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
notify.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertNotify(notify);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("perf/dubbo.test.api.HelloService:1.0.0", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertNotify2() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> notify = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
notify.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertNotify(notify);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("perf/dubbo.test.api.HelloService:1.0.0", service);
assertEquals(expectedRegister, newRegister);
}
// backward compatibility for version 2.0.0
@Test
void testRevertForbid() {
String service = "dubbo.test.api.HelloService";
List<String> forbid = new ArrayList<String>();
forbid.add(service);
Set<URL> subscribed = new HashSet<URL>();
subscribed.add(URL.valueOf("dubbo://127.0.0.1:20880/" + service + "?group=perf&version=1.0.0"));
List<String> newForbid = UrlUtils.revertForbid(forbid, subscribed);
List<String> expectForbid = new ArrayList<String>();
expectForbid.add("perf/" + service + ":1.0.0");
assertEquals(expectForbid, newForbid);
}
@Test
void testRevertForbid2() {
List<String> newForbid = UrlUtils.revertForbid(null, null);
assertNull(newForbid);
}
@Test
void testRevertForbid3() {
String service1 = "dubbo.test.api.HelloService:1.0.0";
String service2 = "dubbo.test.api.HelloService:2.0.0";
List<String> forbid = new ArrayList<String>();
forbid.add(service1);
forbid.add(service2);
List<String> newForbid = UrlUtils.revertForbid(forbid, null);
assertEquals(forbid, newForbid);
}
@Test
void testIsMatch() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch2() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=2.0.0&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch3() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=aa");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch4() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=*");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch5() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=*&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsItemMatch() throws Exception {
assertTrue(UrlUtils.isItemMatch(null, null));
assertTrue(!UrlUtils.isItemMatch("1", null));
assertTrue(!UrlUtils.isItemMatch(null, "1"));
assertTrue(UrlUtils.isItemMatch("1", "1"));
assertTrue(UrlUtils.isItemMatch("*", null));
assertTrue(UrlUtils.isItemMatch("*", "*"));
assertTrue(UrlUtils.isItemMatch("*", "1234"));
assertTrue(!UrlUtils.isItemMatch(null, "*"));
}
@Test
void testIsServiceKeyMatch() throws Exception {
URL url = URL.valueOf("test://127.0.0.1");
URL pattern = url.addParameter(GROUP_KEY, "test")
.addParameter(INTERFACE_KEY, "test")
.addParameter(VERSION_KEY, "test");
URL value = pattern;
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
pattern = pattern.addParameter(GROUP_KEY, "*");
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
pattern = pattern.addParameter(VERSION_KEY, "*");
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
}
@Test
void testGetEmptyUrl() throws Exception {
URL url = UrlUtils.getEmptyUrl("dubbo/a.b.c.Foo:1.0.0", "test");
assertThat(url.toFullString(), equalTo("empty://0.0.0.0/a.b.c.Foo?category=test&group=dubbo&version=1.0.0"));
}
@Test
void testIsMatchGlobPattern() throws Exception {
assertTrue(UrlUtils.isMatchGlobPattern("*", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("", null));
assertFalse(UrlUtils.isMatchGlobPattern("", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("value", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("v*", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("*e", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("v*e", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("$key", "value", URL.valueOf("dubbo://localhost:8080/Foo?key=v*e")));
}
@Test
void testIsMatchUrlWithDefaultPrefix() {
URL url = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?default.version=1.0.0&default.group=test");
assertEquals("1.0.0", url.getVersion());
assertEquals("1.0.0", url.getParameter("default.version"));
URL consumerUrl = URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, url));
URL consumerUrl1 =
URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?default.version=1.0.0&default.group=test");
assertTrue(UrlUtils.isMatch(consumerUrl1, url));
}
@Test
public void testIsConsumer() {
String address1 = "remote://root:alibaba@127.0.0.1:9090";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "consumer://root:alibaba@127.0.0.1:9090";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "consumer://root:alibaba@127.0.0.1";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isConsumer(url1));
assertTrue(UrlUtils.isConsumer(url2));
assertTrue(UrlUtils.isConsumer(url3));
}
@Test
public void testPrivateConstructor() throws Exception {
Constructor<UrlUtils> constructor = UrlUtils.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
assertThrows(InvocationTargetException.class, () -> {
constructor.newInstance();
});
}
@Test
public void testClassifyUrls() {
String address1 = "remote://root:alibaba@127.0.0.1:9090";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "consumer://root:alibaba@127.0.0.1:9090";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "remote://root:alibaba@127.0.0.1";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "consumer://root:alibaba@127.0.0.1";
URL url4 = UrlUtils.parseURL(address4, null);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
urls.add(url4);
List<URL> consumerUrls = UrlUtils.classifyUrls(urls, UrlUtils::isConsumer);
assertEquals(2, consumerUrls.size());
assertTrue(consumerUrls.contains(url2));
assertTrue(consumerUrls.contains(url4));
List<URL> nonConsumerUrls = UrlUtils.classifyUrls(urls, url -> !UrlUtils.isConsumer(url));
assertEquals(2, nonConsumerUrls.size());
assertTrue(nonConsumerUrls.contains(url1));
assertTrue(nonConsumerUrls.contains(url3));
}
@Test
public void testHasServiceDiscoveryRegistryProtocol() {
String address1 = "http://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "service-discovery-registry://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url2 = UrlUtils.parseURL(address2, null);
assertFalse(UrlUtils.hasServiceDiscoveryRegistryProtocol(url1));
assertTrue(UrlUtils.hasServiceDiscoveryRegistryProtocol(url2));
}
private static final String SERVICE_REGISTRY_TYPE = "service";
private static final String REGISTRY_TYPE_KEY = "registry-type";
@Test
public void testHasServiceDiscoveryRegistryTypeKey() {
Map<String, String> parameters1 = new HashMap<>();
parameters1.put(REGISTRY_TYPE_KEY, "value2");
assertFalse(UrlUtils.hasServiceDiscoveryRegistryTypeKey(parameters1));
Map<String, String> parameters2 = new HashMap<>();
parameters2.put(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE);
assertTrue(UrlUtils.hasServiceDiscoveryRegistryTypeKey(parameters2));
}
@Test
public void testIsConfigurator() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "override://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "http://example.com?category=configurators";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isConfigurator(url1));
assertTrue(UrlUtils.isConfigurator(url2));
assertTrue(UrlUtils.isConfigurator(url3));
}
@Test
public void testIsRoute() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "route://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "http://example.com?category=routers";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isRoute(url1));
assertTrue(UrlUtils.isRoute(url2));
assertTrue(UrlUtils.isRoute(url3));
}
@Test
public void testIsProvider() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "override://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "route://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "http://example.com?category=providers";
URL url4 = UrlUtils.parseURL(address4, null);
String address5 = "http://example.com?category=something-else";
URL url5 = UrlUtils.parseURL(address5, null);
assertTrue(UrlUtils.isProvider(url1));
assertFalse(UrlUtils.isProvider(url2));
assertFalse(UrlUtils.isProvider(url3));
assertTrue(UrlUtils.isProvider(url4));
assertFalse(UrlUtils.isProvider(url5));
}
@Test
public void testIsRegistry() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "registry://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "sr://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "custom-registry-protocol://example.com";
URL url4 = UrlUtils.parseURL(address4, null);
assertFalse(UrlUtils.isRegistry(url1));
assertTrue(UrlUtils.isRegistry(url2));
assertFalse(UrlUtils.isRegistry(url3));
assertTrue(UrlUtils.isRegistry(url4));
}
@Test
public void testIsServiceDiscoveryURL() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "service-discovery-registry://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "SERVICE-DISCOVERY-REGISTRY://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "http://example.com?registry-type=service";
URL url4 = UrlUtils.parseURL(address4, null);
url4.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE);
assertFalse(UrlUtils.isServiceDiscoveryURL(url1));
assertTrue(UrlUtils.isServiceDiscoveryURL(url2));
assertTrue(UrlUtils.isServiceDiscoveryURL(url3));
assertTrue(UrlUtils.isServiceDiscoveryURL(url4));
}
}
| 6,479 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.EmptyStackException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class StackTest {
@Test
void testOps() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
assertThat(stack.get(0), equalTo("one"));
assertThat(stack.peek(), equalTo("one"));
assertThat(stack.size(), equalTo(1));
stack.push("two");
assertThat(stack.get(0), equalTo("one"));
assertThat(stack.peek(), equalTo("two"));
assertThat(stack.size(), equalTo(2));
assertThat(stack.set(0, "three"), equalTo("one"));
assertThat(stack.remove(0), equalTo("three"));
assertThat(stack.size(), equalTo(1));
assertThat(stack.isEmpty(), is(false));
assertThat(stack.get(0), equalTo("two"));
assertThat(stack.peek(), equalTo("two"));
assertThat(stack.pop(), equalTo("two"));
assertThat(stack.isEmpty(), is(true));
}
@Test
void testClear() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
stack.push("two");
assertThat(stack.isEmpty(), is(false));
stack.clear();
assertThat(stack.isEmpty(), is(true));
}
@Test
void testIllegalPop() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.pop();
});
}
@Test
void testIllegalPeek() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.peek();
});
}
@Test
void testIllegalGet() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.get(1);
});
}
@Test
void testIllegalGetNegative() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
stack.get(-1);
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
stack.get(-10);
});
}
@Test
void testIllegalSet() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.set(1, "illegal");
});
}
@Test
void testIllegalSetNegative() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.set(-1, "illegal");
});
}
@Test
void testIllegalRemove() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.remove(1);
});
}
@Test
void testIllegalRemoveNegative() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
stack.remove(-2);
});
}
}
| 6,480 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.FieldUtils.findField;
import static org.apache.dubbo.common.utils.FieldUtils.getDeclaredField;
import static org.apache.dubbo.common.utils.FieldUtils.getFieldValue;
import static org.apache.dubbo.common.utils.FieldUtils.setFieldValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* {@link FieldUtils} Test-cases
*
* @since 2.7.6
*/
class FieldUtilsTest {
@Test
void testGetDeclaredField() {
assertEquals("a", getDeclaredField(A.class, "a").getName());
assertEquals("b", getDeclaredField(B.class, "b").getName());
assertEquals("c", getDeclaredField(C.class, "c").getName());
assertNull(getDeclaredField(B.class, "a"));
assertNull(getDeclaredField(C.class, "a"));
}
@Test
void testFindField() {
assertEquals("a", findField(A.class, "a").getName());
assertEquals("a", findField(new A(), "a").getName());
assertEquals("a", findField(B.class, "a").getName());
assertEquals("b", findField(B.class, "b").getName());
assertEquals("a", findField(C.class, "a").getName());
assertEquals("b", findField(C.class, "b").getName());
assertEquals("c", findField(C.class, "c").getName());
}
@Test
void testGetFieldValue() {
assertEquals("a", getFieldValue(new A(), "a"));
assertEquals("a", getFieldValue(new B(), "a"));
assertEquals("b", getFieldValue(new B(), "b"));
assertEquals("a", getFieldValue(new C(), "a"));
assertEquals("b", getFieldValue(new C(), "b"));
assertEquals("c", getFieldValue(new C(), "c"));
}
@Test
void setSetFieldValue() {
A a = new A();
assertEquals("a", setFieldValue(a, "a", "x"));
assertEquals("x", getFieldValue(a, "a"));
}
}
class A {
private String a = "a";
}
class B extends A {
private String b = "b";
}
class C extends B {
private String c = "c";
}
| 6,481 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import javax.lang.model.SourceVersion;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class JRETest {
@Test
@Disabled
void blankSystemVersion() {
System.setProperty("java.version", "");
JRE jre = JRE.currentVersion();
Assertions.assertEquals(JRE.JAVA_8, jre);
}
@Test
void testCurrentVersion() {
// SourceVersion is an enum, which member name is RELEASE_XX.
Assertions.assertEquals(
SourceVersion.latest().name().split("_")[1],
JRE.currentVersion().name().split("_")[1]);
}
}
| 6,482 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
import static org.apache.dubbo.common.utils.StringUtils.splitToList;
import static org.apache.dubbo.common.utils.StringUtils.splitToSet;
import static org.apache.dubbo.common.utils.StringUtils.startsWithIgnoreCase;
import static org.apache.dubbo.common.utils.StringUtils.toCommaDelimitedString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StringUtilsTest {
@Test
void testLength() throws Exception {
assertThat(StringUtils.length(null), equalTo(0));
assertThat(StringUtils.length("abc"), equalTo(3));
}
@Test
void testRepeat() throws Exception {
assertThat(StringUtils.repeat(null, 2), nullValue());
assertThat(StringUtils.repeat("", 0), equalTo(""));
assertThat(StringUtils.repeat("", 2), equalTo(""));
assertThat(StringUtils.repeat("a", 3), equalTo("aaa"));
assertThat(StringUtils.repeat("ab", 2), equalTo("abab"));
assertThat(StringUtils.repeat("a", -2), equalTo(""));
assertThat(StringUtils.repeat(null, null, 2), nullValue());
assertThat(StringUtils.repeat(null, "x", 2), nullValue());
assertThat(StringUtils.repeat("", null, 0), equalTo(""));
assertThat(StringUtils.repeat("", "", 2), equalTo(""));
assertThat(StringUtils.repeat("", "x", 3), equalTo("xx"));
assertThat(StringUtils.repeat("?", ", ", 3), equalTo("?, ?, ?"));
assertThat(StringUtils.repeat('e', 0), equalTo(""));
assertThat(StringUtils.repeat('e', 3), equalTo("eee"));
}
@Test
void testStripEnd() throws Exception {
assertThat(StringUtils.stripEnd(null, "*"), nullValue());
assertThat(StringUtils.stripEnd("", null), equalTo(""));
assertThat(StringUtils.stripEnd("abc", ""), equalTo("abc"));
assertThat(StringUtils.stripEnd("abc", null), equalTo("abc"));
assertThat(StringUtils.stripEnd(" abc", null), equalTo(" abc"));
assertThat(StringUtils.stripEnd("abc ", null), equalTo("abc"));
assertThat(StringUtils.stripEnd(" abc ", null), equalTo(" abc"));
assertThat(StringUtils.stripEnd(" abcyx", "xyz"), equalTo(" abc"));
assertThat(StringUtils.stripEnd("120.00", ".0"), equalTo("12"));
}
@Test
void testReplace() throws Exception {
assertThat(StringUtils.replace(null, "*", "*"), nullValue());
assertThat(StringUtils.replace("", "*", "*"), equalTo(""));
assertThat(StringUtils.replace("any", null, "*"), equalTo("any"));
assertThat(StringUtils.replace("any", "*", null), equalTo("any"));
assertThat(StringUtils.replace("any", "", "*"), equalTo("any"));
assertThat(StringUtils.replace("aba", "a", null), equalTo("aba"));
assertThat(StringUtils.replace("aba", "a", ""), equalTo("b"));
assertThat(StringUtils.replace("aba", "a", "z"), equalTo("zbz"));
assertThat(StringUtils.replace(null, "*", "*", 64), nullValue());
assertThat(StringUtils.replace("", "*", "*", 64), equalTo(""));
assertThat(StringUtils.replace("any", null, "*", 64), equalTo("any"));
assertThat(StringUtils.replace("any", "*", null, 64), equalTo("any"));
assertThat(StringUtils.replace("any", "", "*", 64), equalTo("any"));
assertThat(StringUtils.replace("any", "*", "*", 0), equalTo("any"));
assertThat(StringUtils.replace("abaa", "a", null, -1), equalTo("abaa"));
assertThat(StringUtils.replace("abaa", "a", "", -1), equalTo("b"));
assertThat(StringUtils.replace("abaa", "a", "z", 0), equalTo("abaa"));
assertThat(StringUtils.replace("abaa", "a", "z", 1), equalTo("zbaa"));
assertThat(StringUtils.replace("abaa", "a", "z", 2), equalTo("zbza"));
}
@Test
void testIsBlank() throws Exception {
assertTrue(StringUtils.isBlank(null));
assertTrue(StringUtils.isBlank(""));
assertFalse(StringUtils.isBlank("abc"));
}
@Test
void testIsEmpty() throws Exception {
assertTrue(StringUtils.isEmpty(null));
assertTrue(StringUtils.isEmpty(""));
assertFalse(StringUtils.isEmpty("abc"));
}
@Test
void testIsNoneEmpty() throws Exception {
assertFalse(StringUtils.isNoneEmpty(null));
assertFalse(StringUtils.isNoneEmpty(""));
assertTrue(StringUtils.isNoneEmpty(" "));
assertTrue(StringUtils.isNoneEmpty("abc"));
assertTrue(StringUtils.isNoneEmpty("abc", "def"));
assertFalse(StringUtils.isNoneEmpty("abc", null));
assertFalse(StringUtils.isNoneEmpty("abc", ""));
assertTrue(StringUtils.isNoneEmpty("abc", " "));
}
@Test
void testIsAnyEmpty() throws Exception {
assertTrue(StringUtils.isAnyEmpty(null));
assertTrue(StringUtils.isAnyEmpty(""));
assertFalse(StringUtils.isAnyEmpty(" "));
assertFalse(StringUtils.isAnyEmpty("abc"));
assertFalse(StringUtils.isAnyEmpty("abc", "def"));
assertTrue(StringUtils.isAnyEmpty("abc", null));
assertTrue(StringUtils.isAnyEmpty("abc", ""));
assertFalse(StringUtils.isAnyEmpty("abc", " "));
}
@Test
void testIsNotEmpty() throws Exception {
assertFalse(StringUtils.isNotEmpty(null));
assertFalse(StringUtils.isNotEmpty(""));
assertTrue(StringUtils.isNotEmpty("abc"));
}
@Test
void testIsEquals() throws Exception {
assertTrue(StringUtils.isEquals(null, null));
assertFalse(StringUtils.isEquals(null, ""));
assertTrue(StringUtils.isEquals("abc", "abc"));
assertFalse(StringUtils.isEquals("abc", "ABC"));
}
@Test
void testIsInteger() throws Exception {
assertFalse(StringUtils.isNumber(null));
assertFalse(StringUtils.isNumber(""));
assertTrue(StringUtils.isNumber("123"));
}
@Test
void testParseInteger() throws Exception {
assertThat(StringUtils.parseInteger(null), equalTo(0));
assertThat(StringUtils.parseInteger("123"), equalTo(123));
}
@Test
void testIsJavaIdentifier() throws Exception {
assertThat(StringUtils.isJavaIdentifier(""), is(false));
assertThat(StringUtils.isJavaIdentifier("1"), is(false));
assertThat(StringUtils.isJavaIdentifier("abc123"), is(true));
assertThat(StringUtils.isJavaIdentifier("abc(23)"), is(false));
}
@Test
void testExceptionToString() throws Exception {
assertThat(
StringUtils.toString(new RuntimeException("abc")), containsString("java.lang.RuntimeException: abc"));
}
@Test
void testExceptionToStringWithMessage() throws Exception {
String s = StringUtils.toString("greeting", new RuntimeException("abc"));
assertThat(s, containsString("greeting"));
assertThat(s, containsString("java.lang.RuntimeException: abc"));
}
@Test
void testParseQueryString() throws Exception {
assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key1"), equalTo("value1"));
assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key2"), equalTo("value2"));
assertThat(StringUtils.getQueryStringValue("", "key1"), isEmptyOrNullString());
}
@Test
void testGetServiceKey() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put(GROUP_KEY, "dubbo");
map.put(INTERFACE_KEY, "a.b.c.Foo");
map.put(VERSION_KEY, "1.0.0");
assertThat(StringUtils.getServiceKey(map), equalTo("dubbo/a.b.c.Foo:1.0.0"));
}
@Test
void testToQueryString() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
String queryString = StringUtils.toQueryString(map);
assertThat(queryString, containsString("key1=value1"));
assertThat(queryString, containsString("key2=value2"));
}
@Test
void testJoin() throws Exception {
String[] s = {"1", "2", "3"};
assertEquals(StringUtils.join(s), "123");
assertEquals(StringUtils.join(s, ','), "1,2,3");
assertEquals(StringUtils.join(s, ","), "1,2,3");
}
@Test
void testSplit() throws Exception {
String str = "d,1,2,4";
assertEquals(4, StringUtils.split(str, ',').length);
assertArrayEquals(str.split(","), StringUtils.split(str, ','));
assertEquals(1, StringUtils.split(str, 'a').length);
assertArrayEquals(str.split("a"), StringUtils.split(str, 'a'));
assertEquals(0, StringUtils.split("", 'a').length);
assertEquals(0, StringUtils.split(null, 'a').length);
System.out.println(Arrays.toString(StringUtils.split("boo:and:foo", ':')));
System.out.println(Arrays.toString(StringUtils.split("boo:and:foo", 'o')));
}
@Test
void testSplitToList() throws Exception {
String str = "d,1,2,4";
assertEquals(4, splitToList(str, ',').size());
assertEquals(asList(str.split(",")), splitToList(str, ','));
assertEquals(1, splitToList(str, 'a').size());
assertEquals(asList(str.split("a")), splitToList(str, 'a'));
assertEquals(0, splitToList("", 'a').size());
assertEquals(0, splitToList(null, 'a').size());
}
/**
* Test {@link StringUtils#splitToSet(String, char, boolean)}
*
* @since 2.7.8
*/
@Test
void testSplitToSet() {
String value = "1# 2#3 #4#3";
Set<String> values = splitToSet(value, '#', false);
assertEquals(ofSet("1", " 2", "3 ", "4", "3"), values);
values = splitToSet(value, '#', true);
assertEquals(ofSet("1", "2", "3", "4"), values);
}
@Test
void testTranslate() throws Exception {
String s = "16314";
assertEquals(StringUtils.translate(s, "123456", "abcdef"), "afcad");
assertEquals(StringUtils.translate(s, "123456", "abcd"), "acad");
}
@Test
void testIsContains() throws Exception {
assertThat(StringUtils.isContains("a,b, c", "b"), is(true));
assertThat(StringUtils.isContains("", "b"), is(false));
assertThat(StringUtils.isContains(new String[] {"a", "b", "c"}, "b"), is(true));
assertThat(StringUtils.isContains((String[]) null, null), is(false));
assertTrue(StringUtils.isContains("abc", 'a'));
assertFalse(StringUtils.isContains("abc", 'd'));
assertFalse(StringUtils.isContains("", 'a'));
assertFalse(StringUtils.isContains(null, 'a'));
assertTrue(StringUtils.isNotContains("abc", 'd'));
assertFalse(StringUtils.isNotContains("abc", 'a'));
assertTrue(StringUtils.isNotContains("", 'a'));
assertTrue(StringUtils.isNotContains(null, 'a'));
}
@Test
void testIsNumeric() throws Exception {
assertThat(StringUtils.isNumeric("123", false), is(true));
assertThat(StringUtils.isNumeric("1a3", false), is(false));
assertThat(StringUtils.isNumeric(null, false), is(false));
assertThat(StringUtils.isNumeric("0", true), is(true));
assertThat(StringUtils.isNumeric("0.1", true), is(true));
assertThat(StringUtils.isNumeric("DUBBO", true), is(false));
assertThat(StringUtils.isNumeric("", true), is(false));
assertThat(StringUtils.isNumeric(" ", true), is(false));
assertThat(StringUtils.isNumeric(" ", true), is(false));
assertThat(StringUtils.isNumeric("123.3.3", true), is(false));
assertThat(StringUtils.isNumeric("123.", true), is(true));
assertThat(StringUtils.isNumeric(".123", true), is(true));
assertThat(StringUtils.isNumeric("..123", true), is(false));
}
@Test
void testJoinCollectionString() throws Exception {
List<String> list = new ArrayList<String>();
assertEquals("", StringUtils.join(list, ","));
list.add("v1");
assertEquals("v1", StringUtils.join(list, "-"));
list.add("v2");
list.add("v3");
String out = StringUtils.join(list, ":");
assertEquals("v1:v2:v3", out);
}
@Test
void testCamelToSplitName() throws Exception {
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("abCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("AbCdEf", "-"));
assertEquals("abcdef", StringUtils.camelToSplitName("abcdef", "-"));
// assertEquals("name", StringUtils.camelToSplitName("NAME", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("ab-cd-ef", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("Ab-Cd-Ef", "-"));
assertEquals("Ab_Cd_Ef", StringUtils.camelToSplitName("Ab_Cd_Ef", "-"));
assertEquals("AB_CD_EF", StringUtils.camelToSplitName("AB_CD_EF", "-"));
assertEquals("ab.cd.ef", StringUtils.camelToSplitName("AbCdEf", "."));
// assertEquals("ab.cd.ef", StringUtils.camelToSplitName("ab-cd-ef", "."));
}
@Test
void testSnakeCaseToSplitName() throws Exception {
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("Ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("ab_cd_ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("AB_CD_EF", "-"));
assertEquals("abcdef", StringUtils.snakeToSplitName("abcdef", "-"));
assertEquals("qosEnable", StringUtils.snakeToSplitName("qosEnable", "-"));
assertEquals("name", StringUtils.snakeToSplitName("NAME", "-"));
}
@Test
void testConvertToSplitName() {
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("Ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab_cd_ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("AB_CD_EF", "-"));
assertEquals("abcdef", StringUtils.convertToSplitName("abcdef", "-"));
assertEquals("qos-enable", StringUtils.convertToSplitName("qosEnable", "-"));
assertEquals("name", StringUtils.convertToSplitName("NAME", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("abCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("AbCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab-cd-ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("Ab-Cd-Ef", "-"));
}
@Test
void testToArgumentString() throws Exception {
String s = StringUtils.toArgumentString(new Object[] {"a", 0, Collections.singletonMap("enabled", true)});
assertThat(s, containsString("a,"));
assertThat(s, containsString("0,"));
assertThat(s, containsString("{\"enabled\":true}"));
}
@Test
void testTrim() {
assertEquals("left blank", StringUtils.trim(" left blank"));
assertEquals("right blank", StringUtils.trim("right blank "));
assertEquals("bi-side blank", StringUtils.trim(" bi-side blank "));
}
@Test
void testToURLKey() {
assertEquals("dubbo.tag1", StringUtils.toURLKey("dubbo_tag1"));
assertEquals("dubbo.tag1.tag11", StringUtils.toURLKey("dubbo-tag1_tag11"));
}
@Test
void testToOSStyleKey() {
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo_tag1"));
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo.tag1"));
assertEquals("DUBBO_TAG1_TAG11", StringUtils.toOSStyleKey("dubbo.tag1.tag11"));
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("tag1"));
}
@Test
void testParseParameters() {
String legalStr = "[{key1:value1},{key2:value2}]";
Map<String, String> legalMap = StringUtils.parseParameters(legalStr);
assertEquals(2, legalMap.size());
assertEquals("value2", legalMap.get("key2"));
String str = StringUtils.encodeParameters(legalMap);
assertEqualsWithoutSpaces(legalStr, str);
String legalSpaceStr = "[{key1: value1}, {key2 :value2}]";
Map<String, String> legalSpaceMap = StringUtils.parseParameters(legalSpaceStr);
assertEquals(2, legalSpaceMap.size());
assertEquals("value2", legalSpaceMap.get("key2"));
str = StringUtils.encodeParameters(legalSpaceMap);
assertEqualsWithoutSpaces(legalSpaceStr, str);
String legalSpecialStr = "[{key-1: value*.1}, {key.2 :value*.-_2}]";
Map<String, String> legalSpecialMap = StringUtils.parseParameters(legalSpecialStr);
assertEquals(2, legalSpecialMap.size());
assertEquals("value*.1", legalSpecialMap.get("key-1"));
assertEquals("value*.-_2", legalSpecialMap.get("key.2"));
str = StringUtils.encodeParameters(legalSpecialMap);
assertEqualsWithoutSpaces(legalSpecialStr, str);
String illegalStr = "[{key=value},{aa:bb}]";
Map<String, String> illegalMap = StringUtils.parseParameters(illegalStr);
assertEquals(0, illegalMap.size());
str = StringUtils.encodeParameters(illegalMap);
assertEquals(null, str);
String emptyMapStr = "[]";
Map<String, String> emptyMap = StringUtils.parseParameters(emptyMapStr);
assertEquals(0, emptyMap.size());
}
@Test
void testEncodeParameters() {
Map<String, String> nullValueMap = new LinkedHashMap<>();
nullValueMap.put("client", null);
String str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
Map<String, String> blankValueMap = new LinkedHashMap<>();
blankValueMap.put("client", " ");
str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
blankValueMap = new LinkedHashMap<>();
blankValueMap.put("client", "");
str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
}
private void assertEqualsWithoutSpaces(String expect, String actual) {
assertEquals(expect.replaceAll(" ", ""), actual.replaceAll(" ", ""));
}
/**
* Test {@link StringUtils#toCommaDelimitedString(String, String...)}
* @since 2.7.8
*/
@Test
void testToCommaDelimitedString() {
String value = toCommaDelimitedString(null);
assertNull(value);
value = toCommaDelimitedString(null, null);
assertNull(value);
value = toCommaDelimitedString("");
assertEquals("", value);
value = toCommaDelimitedString("one");
assertEquals("one", value);
value = toCommaDelimitedString("one", "two");
assertEquals("one,two", value);
value = toCommaDelimitedString("one", "two", "three");
assertEquals("one,two,three", value);
}
@Test
void testStartsWithIgnoreCase() {
assertTrue(startsWithIgnoreCase("dubbo.application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("dubbo.Application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("Dubbo.application.name", "dubbo.application."));
}
}
| 6,483 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class NamedThreadFactoryTest {
private static final int INITIAL_THREAD_NUM = 1;
@Test
void testNewThread() {
NamedThreadFactory factory = new NamedThreadFactory();
Thread t = factory.newThread(Mockito.mock(Runnable.class));
assertThat(t.getName(), allOf(containsString("pool-"), containsString("-thread-")));
assertFalse(t.isDaemon());
// since security manager is not installed.
assertSame(t.getThreadGroup(), Thread.currentThread().getThreadGroup());
}
@Test
void testPrefixAndDaemon() {
NamedThreadFactory factory = new NamedThreadFactory("prefix", true);
Thread t = factory.newThread(Mockito.mock(Runnable.class));
assertThat(t.getName(), allOf(containsString("prefix-"), containsString("-thread-")));
assertTrue(t.isDaemon());
}
@Test
public void testGetThreadNum() {
NamedThreadFactory threadFactory = new NamedThreadFactory();
AtomicInteger threadNum = threadFactory.getThreadNum();
assertNotNull(threadNum);
assertEquals(INITIAL_THREAD_NUM, threadNum.get());
}
@Test
public void testGetThreadGroup() {
NamedThreadFactory threadFactory = new NamedThreadFactory();
ThreadGroup threadGroup = threadFactory.getThreadGroup();
assertNotNull(threadGroup);
}
}
| 6,484 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ArrayUtilsTest {
@Test
void isEmpty() {
assertTrue(ArrayUtils.isEmpty(null));
assertTrue(ArrayUtils.isEmpty(new Object[0]));
assertFalse(ArrayUtils.isEmpty(new Object[] {"abc"}));
}
@Test
void isNotEmpty() {
assertFalse(ArrayUtils.isNotEmpty(null));
assertFalse(ArrayUtils.isNotEmpty(new Object[0]));
assertTrue(ArrayUtils.isNotEmpty(new Object[] {"abc"}));
}
}
| 6,485 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LRU2CacheTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LRU2CacheTest {
@Test
void testCache() {
LRU2Cache<String, Integer> cache = new LRU2Cache<String, Integer>(3);
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertFalse(cache.containsKey("one"));
assertFalse(cache.containsKey("two"));
assertFalse(cache.containsKey("three"));
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertThat(cache.get("one"), equalTo(1));
assertThat(cache.get("two"), equalTo(2));
assertThat(cache.get("three"), equalTo(3));
assertThat(cache.size(), equalTo(3));
cache.put("four", 4);
cache.put("four", 4);
assertThat(cache.size(), equalTo(3));
assertFalse(cache.containsKey("one"));
assertTrue(cache.containsKey("two"));
assertTrue(cache.containsKey("three"));
assertTrue(cache.containsKey("four"));
cache.remove("four");
assertThat(cache.size(), equalTo(2));
cache.put("five", 5);
cache.put("five", 5);
assertFalse(cache.containsKey("four"));
assertTrue(cache.containsKey("five"));
assertTrue(cache.containsKey("two"));
assertTrue(cache.containsKey("three"));
assertThat(cache.size(), equalTo(3));
cache.put("six", 6);
assertFalse(cache.containsKey("six"));
}
@Test
void testCapacity() {
LRU2Cache<String, Integer> cache = new LRU2Cache<String, Integer>();
assertThat(cache.getMaxCapacity(), equalTo(1000));
cache.setMaxCapacity(10);
assertThat(cache.getMaxCapacity(), equalTo(10));
}
}
| 6,486 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class LFUCacheTest {
@Test
void testCacheEviction() {
LFUCache<String, Integer> cache = new LFUCache<>(8, 0.8f);
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertThat(cache.get("one"), equalTo(1));
assertThat(cache.get("two"), equalTo(2));
assertThat(cache.get("three"), equalTo(3));
assertThat(cache.getSize(), equalTo(3));
cache.put("four", 4);
assertThat(cache.getSize(), equalTo(4));
cache.put("five", 5);
cache.put("six", 6);
assertThat(cache.getSize(), equalTo(6));
cache.put("seven", 7);
cache.put("eight", 8);
cache.put("nine", 9);
assertThat(cache.getSize(), equalTo(2));
}
@Test
void testCacheRemove() {
LFUCache<String, Integer> cache = new LFUCache<>(8, 0.8f);
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertThat(cache.get("one"), equalTo(1));
assertThat(cache.get("two"), equalTo(2));
assertThat(cache.get("three"), equalTo(3));
assertThat(cache.getSize(), equalTo(3));
cache.put("four", 4);
assertThat(cache.getSize(), equalTo(4));
cache.remove("four");
assertThat(cache.getSize(), equalTo(3));
cache.put("five", 5);
assertThat(cache.getSize(), equalTo(4));
cache.put("six", 6);
assertThat(cache.getSize(), equalTo(5));
}
@Test
void testDefaultCapacity() {
LFUCache<String, Integer> cache = new LFUCache<>();
assertThat(cache.getCapacity(), equalTo(1000));
}
@Test
void testErrorConstructArguments() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(0, 0.8f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(-1, 0.8f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(100, 0.0f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(100, -0.1f));
}
}
| 6,487 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogHelperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.logger.Logger;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class LogHelperTest {
@Test
void testTrace() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isTraceEnabled()).thenReturn(true);
LogHelper.trace(logger, "trace");
verify(logger).trace("trace");
Throwable t = new RuntimeException();
LogHelper.trace(logger, t);
verify(logger).trace(t);
LogHelper.trace(logger, "trace", t);
verify(logger).trace("trace", t);
}
@Test
void testDebug() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isDebugEnabled()).thenReturn(true);
LogHelper.debug(logger, "debug");
verify(logger).debug("debug");
Throwable t = new RuntimeException();
LogHelper.debug(logger, t);
verify(logger).debug(t);
LogHelper.debug(logger, "debug", t);
verify(logger).debug("debug", t);
}
@Test
void testInfo() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isInfoEnabled()).thenReturn(true);
LogHelper.info(logger, "info");
verify(logger).info("info");
Throwable t = new RuntimeException();
LogHelper.info(logger, t);
verify(logger).info(t);
LogHelper.info(logger, "info", t);
verify(logger).info("info", t);
}
@Test
void testWarn() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isWarnEnabled()).thenReturn(true);
LogHelper.warn(logger, "warn");
verify(logger).warn("warn");
Throwable t = new RuntimeException();
LogHelper.warn(logger, t);
verify(logger).warn(t);
LogHelper.warn(logger, "warn", t);
verify(logger).warn("warn", t);
}
@Test
void testError() {
Logger logger = Mockito.mock(Logger.class);
when(logger.isErrorEnabled()).thenReturn(true);
LogHelper.error(logger, "error");
verify(logger).error("error");
Throwable t = new RuntimeException();
LogHelper.error(logger, t);
verify(logger).error(t);
LogHelper.error(logger, "error", t);
verify(logger).error("error", t);
}
}
| 6,488 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
/**
* MyEnum
*/
public enum MyEnum {
A,
B
}
| 6,489 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.net.UnknownHostException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class CIDRUtilsTest {
@Test
void testIpv4() throws UnknownHostException {
CIDRUtils cidrUtils = new CIDRUtils("192.168.1.0/26");
Assertions.assertTrue(cidrUtils.isInRange("192.168.1.63"));
Assertions.assertFalse(cidrUtils.isInRange("192.168.1.65"));
cidrUtils = new CIDRUtils("192.168.1.192/26");
Assertions.assertTrue(cidrUtils.isInRange("192.168.1.199"));
Assertions.assertFalse(cidrUtils.isInRange("192.168.1.190"));
}
@Test
void testIpv6() throws UnknownHostException {
CIDRUtils cidrUtils = new CIDRUtils("234e:0:4567::3d/64");
Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::3e"));
Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::ffff:3e"));
Assertions.assertFalse(cidrUtils.isInRange("234e:1:4567::3d"));
Assertions.assertFalse(cidrUtils.isInRange("234e:0:4567:1::3d"));
cidrUtils = new CIDRUtils("3FFE:FFFF:0:CC00::/54");
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC00::dd"));
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC00:0000:eeee:0909:dd"));
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC0F:0000:eeee:0909:dd"));
Assertions.assertFalse(cidrUtils.isInRange("3EFE:FFFE:0:C107::dd"));
Assertions.assertFalse(cidrUtils.isInRange("1FFE:FFFE:0:CC00::dd"));
}
}
| 6,490 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class HolderTest {
@Test
void testSetAndGet() throws Exception {
Holder<String> holder = new Holder<String>();
String message = "hello";
holder.set(message);
assertThat(holder.get(), is(message));
}
}
| 6,491 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.model.Person;
import org.apache.dubbo.common.model.SerializablePerson;
import org.apache.dubbo.common.model.User;
import org.apache.dubbo.common.model.person.Ageneric;
import org.apache.dubbo.common.model.person.Bgeneric;
import org.apache.dubbo.common.model.person.BigPerson;
import org.apache.dubbo.common.model.person.Cgeneric;
import org.apache.dubbo.common.model.person.Dgeneric;
import org.apache.dubbo.common.model.person.FullAddress;
import org.apache.dubbo.common.model.person.PersonInfo;
import org.apache.dubbo.common.model.person.PersonMap;
import org.apache.dubbo.common.model.person.PersonStatus;
import org.apache.dubbo.common.model.person.Phone;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PojoUtilsTest {
BigPerson bigPerson;
{
bigPerson = new BigPerson();
bigPerson.setPersonId("id1");
bigPerson.setLoginName("name1");
bigPerson.setStatus(PersonStatus.ENABLED);
bigPerson.setEmail("abc@123.com");
bigPerson.setPenName("pname");
ArrayList<Phone> phones = new ArrayList<Phone>();
Phone phone1 = new Phone("86", "0571", "11223344", "001");
Phone phone2 = new Phone("86", "0571", "11223344", "002");
phones.add(phone1);
phones.add(phone2);
PersonInfo pi = new PersonInfo();
pi.setPhones(phones);
Phone fax = new Phone("86", "0571", "11223344", null);
pi.setFax(fax);
FullAddress addr = new FullAddress("CN", "zj", "1234", "Road1", "333444");
pi.setFullAddress(addr);
pi.setMobileNo("1122334455");
pi.setMale(true);
pi.setDepartment("b2b");
pi.setHomepageUrl("www.abc.com");
pi.setJobTitle("dev");
pi.setName("name2");
bigPerson.setInfoProfile(pi);
}
private static Child newChild(String name, int age) {
Child result = new Child();
result.setName(name);
result.setAge(age);
return result;
}
public void assertObject(Object data) {
assertObject(data, null);
}
public void assertObject(Object data, Type type) {
Object generalize = PojoUtils.generalize(data);
Object realize = PojoUtils.realize(generalize, data.getClass(), type);
assertEquals(data, realize);
}
public <T> void assertArrayObject(T[] data) {
Object generalize = PojoUtils.generalize(data);
@SuppressWarnings("unchecked")
T[] realize = (T[]) PojoUtils.realize(generalize, data.getClass());
assertArrayEquals(data, realize);
}
@Test
void test_primitive() throws Exception {
assertObject(Boolean.TRUE);
assertObject(Boolean.FALSE);
assertObject(Byte.valueOf((byte) 78));
assertObject('a');
assertObject('中');
assertObject(Short.valueOf((short) 37));
assertObject(78);
assertObject(123456789L);
assertObject(3.14F);
assertObject(3.14D);
}
@Test
void test_pojo() throws Exception {
assertObject(new Person());
assertObject(new BasicTestData(false, '\0', (byte) 0, (short) 0, 0, 0L, 0F, 0D));
assertObject(new SerializablePerson(Character.MIN_VALUE, false));
}
@Test
void test_has_no_nullary_constructor_pojo() {
assertObject(new User(1, "fibbery"));
}
@Test
void test_Map_List_pojo() throws Exception {
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
List<Object> list = new ArrayList<Object>();
list.add(new Person());
list.add(new SerializablePerson(Character.MIN_VALUE, false));
map.put("k", list);
Object generalize = PojoUtils.generalize(map);
Object realize = PojoUtils.realize(generalize, Map.class);
assertEquals(map, realize);
}
@Test
void test_PrimitiveArray() throws Exception {
assertObject(new boolean[] {true, false});
assertObject(new Boolean[] {true, false, true});
assertObject(new byte[] {1, 12, 28, 78});
assertObject(new Byte[] {1, 12, 28, 78});
assertObject(new char[] {'a', '中', '无'});
assertObject(new Character[] {'a', '中', '无'});
assertObject(new short[] {37, 39, 12});
assertObject(new Short[] {37, 39, 12});
assertObject(new int[] {37, -39, 12456});
assertObject(new Integer[] {37, -39, 12456});
assertObject(new long[] {37L, -39L, 123456789L});
assertObject(new Long[] {37L, -39L, 123456789L});
assertObject(new float[] {37F, -3.14F, 123456.7F});
assertObject(new Float[] {37F, -39F, 123456.7F});
assertObject(new double[] {37D, -3.14D, 123456.7D});
assertObject(new Double[] {37D, -39D, 123456.7D});
assertArrayObject(new Boolean[] {true, false, true});
assertArrayObject(new Byte[] {1, 12, 28, 78});
assertArrayObject(new Character[] {'a', '中', '无'});
assertArrayObject(new Short[] {37, 39, 12});
assertArrayObject(new Integer[] {37, -39, 12456});
assertArrayObject(new Long[] {37L, -39L, 123456789L});
assertArrayObject(new Float[] {37F, -39F, 123456.7F});
assertArrayObject(new Double[] {37D, -39D, 123456.7D});
assertObject(new int[][] {{37, -39, 12456}});
assertObject(new Integer[][][] {{{37, -39, 12456}}});
assertArrayObject(new Integer[] {37, -39, 12456});
}
@Test
void test_PojoArray() throws Exception {
Person[] array = new Person[2];
array[0] = new Person();
{
Person person = new Person();
person.setName("xxxx");
array[1] = person;
}
assertArrayObject(array);
}
@Test
void testArrayToCollection() throws Exception {
Person[] array = new Person[2];
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
array[0] = person1;
array[1] = person2;
Object o = PojoUtils.realize(PojoUtils.generalize(array), LinkedList.class);
assertTrue(o instanceof LinkedList);
assertEquals(((List) o).get(0), person1);
assertEquals(((List) o).get(1), person2);
}
@Test
void testCollectionToArray() throws Exception {
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
List<Person> list = new LinkedList<Person>();
list.add(person1);
list.add(person2);
Object o = PojoUtils.realize(PojoUtils.generalize(list), Person[].class);
assertTrue(o instanceof Person[]);
assertEquals(((Person[]) o)[0], person1);
assertEquals(((Person[]) o)[1], person2);
}
@Test
void testMapToEnum() throws Exception {
Map map = new HashMap();
map.put("name", "MONDAY");
Object o = PojoUtils.realize(map, Day.class);
assertEquals(o, Day.MONDAY);
}
@Test
void testGeneralizeEnumArray() throws Exception {
Object days = new Enum[] {Day.FRIDAY, Day.SATURDAY};
Object o = PojoUtils.generalize(days);
assertTrue(o instanceof String[]);
assertEquals(((String[]) o)[0], "FRIDAY");
assertEquals(((String[]) o)[1], "SATURDAY");
}
@Test
void testGeneralizePersons() throws Exception {
Object persons = new Person[] {new Person(), new Person()};
Object o = PojoUtils.generalize(persons);
assertTrue(o instanceof Object[]);
assertEquals(((Object[]) o).length, 2);
}
@Test
void testMapToInterface() throws Exception {
Map map = new HashMap();
map.put("content", "greeting");
map.put("from", "dubbo");
map.put("urgent", true);
Object o = PojoUtils.realize(map, Message.class);
Message message = (Message) o;
assertThat(message.getContent(), equalTo("greeting"));
assertThat(message.getFrom(), equalTo("dubbo"));
assertTrue(message.isUrgent());
}
@Test
void testJsonObjectToMap() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setMap", Map.class);
assertNotNull(method);
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", "test");
@SuppressWarnings("unchecked")
Map<Integer, Object> value = (Map<Integer, Object>)
PojoUtils.realize(jsonObject, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
assertEquals("test", value.get(1));
}
@Test
void testListJsonObjectToListMap() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setListMap", List.class);
assertNotNull(method);
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", "test");
List<JSONObject> list = new ArrayList<>(1);
list.add(jsonObject);
@SuppressWarnings("unchecked")
List<Map<Integer, Object>> result = (List<Map<Integer, Object>>)
PojoUtils.realize(list, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), result);
assertEquals("test", result.get(0).get(1));
}
public void setMap(Map<Integer, Object> map) {}
public void setListMap(List<Map<Integer, Object>> list) {}
@Test
void testException() throws Exception {
Map map = new HashMap();
map.put("message", "dubbo exception");
Object o = PojoUtils.realize(map, RuntimeException.class);
assertEquals(((Throwable) o).getMessage(), "dubbo exception");
}
@Test
void testIsPojo() throws Exception {
assertFalse(PojoUtils.isPojo(boolean.class));
assertFalse(PojoUtils.isPojo(Map.class));
assertFalse(PojoUtils.isPojo(List.class));
assertTrue(PojoUtils.isPojo(Person.class));
}
public List<Person> returnListPersonMethod() {
return null;
}
public BigPerson returnBigPersonMethod() {
return null;
}
public Type getType(String methodName) {
Method method;
try {
method = getClass().getDeclaredMethod(methodName, new Class<?>[] {});
} catch (Exception e) {
throw new IllegalStateException(e);
}
Type gtype = method.getGenericReturnType();
return gtype;
}
@Test
void test_simpleCollection() throws Exception {
Type gtype = getType("returnListPersonMethod");
List<Person> list = new ArrayList<Person>();
list.add(new Person());
{
Person person = new Person();
person.setName("xxxx");
list.add(person);
}
assertObject(list, gtype);
}
@Test
void test_total() throws Exception {
Object generalize = PojoUtils.generalize(bigPerson);
Type gtype = getType("returnBigPersonMethod");
Object realize = PojoUtils.realize(generalize, BigPerson.class, gtype);
assertEquals(bigPerson, realize);
}
@Test
void test_total_Array() throws Exception {
Object[] persons = new Object[] {bigPerson, bigPerson, bigPerson};
Object generalize = PojoUtils.generalize(persons);
Object[] realize = (Object[]) PojoUtils.realize(generalize, Object[].class);
assertArrayEquals(persons, realize);
}
@Test
void test_Loop_pojo() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Object generalize = PojoUtils.generalize(p);
Parent parent = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
void test_Loop_Map() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", "v");
map.put("m", map);
assertSame(map, map.get("m"));
System.out.println(map);
Object generalize = PojoUtils.generalize(map);
System.out.println(generalize);
@SuppressWarnings("unchecked")
Map<String, Object> ret = (Map<String, Object>) PojoUtils.realize(generalize, Map.class);
System.out.println(ret);
assertEquals("v", ret.get("k"));
assertSame(ret, ret.get("m"));
}
@Test
void test_LoopPojoInMap() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", p);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> realize =
(Map<String, Object>) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType"));
Parent parent = (Parent) realize.get("k");
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
void test_LoopPojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
Object[] objects = PojoUtils.realize(
new Object[] {generalize}, new Class[] {List.class}, new Type[] {getType("getListGenericType")});
assertTrue(((List) objects[0]).get(0) instanceof Parent);
}
@Test
void test_PojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
}
public void setLong(long l) {}
public void setInt(int l) {}
public List<Parent> getListGenericType() {
return null;
}
public Map<String, Parent> getMapGenericType() {
return null;
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
void test_realize_LongPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setLong", long.class);
assertNotNull(method);
Object value = PojoUtils.realize(
"563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
void test_realize_IntPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setInt", int.class);
assertNotNull(method);
Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
@Test
void testStackOverflow() throws Exception {
Parent parent = Parent.getNewParent();
parent.setAge(Integer.MAX_VALUE);
String name = UUID.randomUUID().toString();
parent.setName(name);
Object generalize = PojoUtils.generalize(parent);
assertTrue(generalize instanceof Map);
Map map = (Map) generalize;
assertEquals(Integer.MAX_VALUE, map.get("age"));
assertEquals(name, map.get("name"));
Parent realize = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(Integer.MAX_VALUE, realize.getAge());
assertEquals(name, realize.getName());
}
@Test
void testGenerializeAndRealizeClass() throws Exception {
Object generalize = PojoUtils.generalize(Integer.class);
assertEquals(Integer.class.getName(), generalize);
Object real = PojoUtils.realize(generalize, Integer.class.getClass());
assertEquals(Integer.class, real);
generalize = PojoUtils.generalize(int[].class);
assertEquals(int[].class.getName(), generalize);
real = PojoUtils.realize(generalize, int[].class.getClass());
assertEquals(int[].class, real);
}
@Test
void testPublicField() throws Exception {
Parent parent = new Parent();
parent.gender = "female";
parent.email = "email@host.com";
parent.setEmail("securityemail@host.com");
Child child = new Child();
parent.setChild(child);
child.gender = "male";
child.setAge(20);
child.setParent(parent);
Object obj = PojoUtils.generalize(parent);
Parent realizedParent = (Parent) PojoUtils.realize(obj, Parent.class);
Assertions.assertEquals(parent.gender, realizedParent.gender);
Assertions.assertEquals(child.gender, parent.getChild().gender);
Assertions.assertEquals(child.age, realizedParent.getChild().getAge());
Assertions.assertEquals(parent.getEmail(), realizedParent.getEmail());
Assertions.assertNull(realizedParent.email);
}
@Test
void testMapField() throws Exception {
TestData data = new TestData();
Child child = newChild("first", 1);
data.addChild(child);
child = newChild("second", 2);
data.addChild(child);
child = newChild("third", 3);
data.addChild(child);
data.setList(Arrays.asList(newChild("forth", 4)));
Object obj = PojoUtils.generalize(data);
Assertions.assertEquals(3, data.getChildren().size());
assertSame(data.getChildren().get("first").getClass(), Child.class);
Assertions.assertEquals(1, data.getList().size());
assertSame(data.getList().get(0).getClass(), Child.class);
TestData realizadData = (TestData) PojoUtils.realize(obj, TestData.class);
Assertions.assertEquals(
data.getChildren().size(), realizadData.getChildren().size());
Assertions.assertEquals(
data.getChildren().keySet(), realizadData.getChildren().keySet());
for (Map.Entry<String, Child> entry : data.getChildren().entrySet()) {
Child c = realizadData.getChildren().get(entry.getKey());
Assertions.assertNotNull(c);
Assertions.assertEquals(entry.getValue().getName(), c.getName());
Assertions.assertEquals(entry.getValue().getAge(), c.getAge());
}
Assertions.assertEquals(1, realizadData.getList().size());
Assertions.assertEquals(
data.getList().get(0).getName(), realizadData.getList().get(0).getName());
Assertions.assertEquals(
data.getList().get(0).getAge(), realizadData.getList().get(0).getAge());
}
@Test
void testRealize() throws Exception {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Object obj = PojoUtils.generalize(map);
assertTrue(obj instanceof LinkedHashMap);
Object outputObject = PojoUtils.realize(map, LinkedHashMap.class);
assertTrue(outputObject instanceof LinkedHashMap);
Object[] objects = PojoUtils.realize(new Object[] {map}, new Class[] {LinkedHashMap.class});
assertTrue(objects[0] instanceof LinkedHashMap);
assertEquals(objects[0], outputObject);
}
@Test
void testRealizeLinkedList() throws Exception {
LinkedList<Person> input = new LinkedList<Person>();
Person person = new Person();
person.setAge(37);
input.add(person);
Object obj = PojoUtils.generalize(input);
assertTrue(obj instanceof List);
assertTrue(input.get(0) instanceof Person);
Object output = PojoUtils.realize(obj, LinkedList.class);
assertTrue(output instanceof LinkedList);
}
@Test
void testPojoList() throws Exception {
ListResult<Parent> result = new ListResult<Parent>();
List<Parent> list = new ArrayList<Parent>();
Parent parent = new Parent();
parent.setAge(Integer.MAX_VALUE);
parent.setName("zhangsan");
list.add(parent);
result.setResult(list);
Object generializeObject = PojoUtils.generalize(result);
Object realizeObject = PojoUtils.realize(generializeObject, ListResult.class);
assertTrue(realizeObject instanceof ListResult);
ListResult listResult = (ListResult) realizeObject;
List l = listResult.getResult();
assertEquals(1, l.size());
assertTrue(l.get(0) instanceof Parent);
Parent realizeParent = (Parent) l.get(0);
Assertions.assertEquals(parent.getName(), realizeParent.getName());
Assertions.assertEquals(parent.getAge(), realizeParent.getAge());
}
@Test
void testListPojoListPojo() throws Exception {
InnerPojo<Parent> parentList = new InnerPojo<Parent>();
Parent parent = new Parent();
parent.setName("zhangsan");
parent.setAge(Integer.MAX_VALUE);
parentList.setList(Arrays.asList(parent));
ListResult<InnerPojo<Parent>> list = new ListResult<InnerPojo<Parent>>();
list.setResult(Arrays.asList(parentList));
Object generializeObject = PojoUtils.generalize(list);
Object realizeObject = PojoUtils.realize(generializeObject, ListResult.class);
assertTrue(realizeObject instanceof ListResult);
ListResult realizeList = (ListResult) realizeObject;
List realizeInnerList = realizeList.getResult();
Assertions.assertEquals(1, realizeInnerList.size());
assertTrue(realizeInnerList.get(0) instanceof InnerPojo);
InnerPojo realizeParentList = (InnerPojo) realizeInnerList.get(0);
Assertions.assertEquals(1, realizeParentList.getList().size());
assertTrue(realizeParentList.getList().get(0) instanceof Parent);
Parent realizeParent = (Parent) realizeParentList.getList().get(0);
Assertions.assertEquals(parent.getName(), realizeParent.getName());
Assertions.assertEquals(parent.getAge(), realizeParent.getAge());
}
@Test
void testDateTimeTimestamp() throws Exception {
String dateStr = "2018-09-12";
String timeStr = "10:12:33";
String dateTimeStr = "2018-09-12 10:12:33";
String[] dateFormat = new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"};
// java.util.Date
Object date = PojoUtils.realize(dateTimeStr, Date.class, (Type) Date.class);
assertEquals(Date.class, date.getClass());
assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(date));
// java.sql.Time
Object time = PojoUtils.realize(dateTimeStr, java.sql.Time.class, (Type) java.sql.Time.class);
assertEquals(java.sql.Time.class, time.getClass());
assertEquals(timeStr, new SimpleDateFormat(dateFormat[2]).format(time));
// java.sql.Date
Object sqlDate = PojoUtils.realize(dateTimeStr, java.sql.Date.class, (Type) java.sql.Date.class);
assertEquals(java.sql.Date.class, sqlDate.getClass());
assertEquals(dateStr, new SimpleDateFormat(dateFormat[1]).format(sqlDate));
// java.sql.Timestamp
Object timestamp = PojoUtils.realize(dateTimeStr, java.sql.Timestamp.class, (Type) java.sql.Timestamp.class);
assertEquals(java.sql.Timestamp.class, timestamp.getClass());
assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(timestamp));
}
@Test
void testIntToBoolean() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "myname");
map.put("male", 1);
map.put("female", 0);
PersonInfo personInfo = (PersonInfo) PojoUtils.realize(map, PersonInfo.class);
assertEquals("myname", personInfo.getName());
assertTrue(personInfo.isMale());
assertFalse(personInfo.isFemale());
}
@Test
void testRealizeCollectionWithNullElement() {
LinkedList<String> listStr = new LinkedList<>();
listStr.add("arrayValue");
listStr.add(null);
HashSet<String> setStr = new HashSet<>();
setStr.add("setValue");
setStr.add(null);
Object listResult = PojoUtils.realize(listStr, LinkedList.class);
assertEquals(LinkedList.class, listResult.getClass());
assertEquals(listResult, listStr);
Object setResult = PojoUtils.realize(setStr, HashSet.class);
assertEquals(HashSet.class, setResult.getClass());
assertEquals(setResult, setStr);
}
@Test
void testJava8Time() {
Object localDateTimeGen = PojoUtils.generalize(LocalDateTime.now());
Object localDateTime = PojoUtils.realize(localDateTimeGen, LocalDateTime.class);
assertEquals(localDateTimeGen, localDateTime.toString());
Object localDateGen = PojoUtils.generalize(LocalDate.now());
Object localDate = PojoUtils.realize(localDateGen, LocalDate.class);
assertEquals(localDateGen, localDate.toString());
Object localTimeGen = PojoUtils.generalize(LocalTime.now());
Object localTime = PojoUtils.realize(localTimeGen, LocalTime.class);
assertEquals(localTimeGen, localTime.toString());
}
@Test
public void testJSONObjectToPersonMapPojo() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("personId", "1");
jsonObject.put("personName", "hand");
Object result = PojoUtils.realize(jsonObject, PersonMap.class);
assertEquals(PersonMap.class, result.getClass());
}
protected PersonInfo createPersonInfoByName(String name) {
PersonInfo dataPerson = new PersonInfo();
dataPerson.setName(name);
return dataPerson;
}
protected Ageneric<PersonInfo> createAGenericPersonInfo(String name) {
Ageneric<PersonInfo> ret = new Ageneric();
ret.setData(createPersonInfoByName(name));
return ret;
}
protected Bgeneric<PersonInfo> createBGenericPersonInfo(String name) {
Bgeneric<PersonInfo> ret = new Bgeneric();
ret.setData(createPersonInfoByName(name));
return ret;
}
@Test
public void testPojoGeneric1() throws NoSuchMethodException {
String personName = "testName";
{
Ageneric<PersonInfo> genericPersonInfo = createAGenericPersonInfo(personName);
Object o = JSON.toJSON(genericPersonInfo);
{
Ageneric personInfo = (Ageneric) PojoUtils.realize(o, Ageneric.class);
assertEquals(Ageneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createAGenericPersonInfo", String.class));
Ageneric personInfo = (Ageneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Ageneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) personInfo.getData()).getName());
}
}
{
Bgeneric<PersonInfo> genericPersonInfo = createBGenericPersonInfo(personName);
Object o = JSON.toJSON(genericPersonInfo);
{
Bgeneric personInfo = (Bgeneric) PojoUtils.realize(o, Bgeneric.class);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createBGenericPersonInfo", String.class));
Bgeneric personInfo = (Bgeneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) personInfo.getData()).getName());
}
}
}
protected Ageneric<Ageneric<PersonInfo>> createAGenericLoop(String name) {
Ageneric<Ageneric<PersonInfo>> ret = new Ageneric();
ret.setData(createAGenericPersonInfo(name));
return ret;
}
protected Bgeneric<Ageneric<PersonInfo>> createBGenericWithAgeneric(String name) {
Bgeneric<Ageneric<PersonInfo>> ret = new Bgeneric();
ret.setData(createAGenericPersonInfo(name));
return ret;
}
@Test
public void testPojoGeneric2() throws NoSuchMethodException {
String personName = "testName";
{
Ageneric<Ageneric<PersonInfo>> generic2PersonInfo = createAGenericLoop(personName);
Object o = JSON.toJSON(generic2PersonInfo);
{
Ageneric personInfo = (Ageneric) PojoUtils.realize(o, Ageneric.class);
assertEquals(Ageneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createAGenericLoop", String.class));
Ageneric personInfo = (Ageneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Ageneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), Ageneric.class);
assertEquals(Ageneric.NAME, ((Ageneric) personInfo.getData()).getName());
assertEquals(((Ageneric) personInfo.getData()).getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) ((Ageneric) personInfo.getData()).getData()).getName());
}
}
{
Bgeneric<Ageneric<PersonInfo>> generic = createBGenericWithAgeneric(personName);
Object o = JSON.toJSON(generic);
{
Ageneric personInfo = (Ageneric) PojoUtils.realize(o, Ageneric.class);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createBGenericWithAgeneric", String.class));
Bgeneric personInfo = (Bgeneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), Ageneric.class);
assertEquals(Ageneric.NAME, ((Ageneric) personInfo.getData()).getName());
assertEquals(((Ageneric) personInfo.getData()).getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) ((Ageneric) personInfo.getData()).getData()).getName());
}
}
}
protected Cgeneric<PersonInfo> createCGenericPersonInfo(String name) {
Cgeneric<PersonInfo> ret = new Cgeneric();
ret.setData(createPersonInfoByName(name));
ret.setA(createAGenericPersonInfo(name));
ret.setB(createBGenericPersonInfo(name));
return ret;
}
@Test
public void testPojoGeneric3() throws NoSuchMethodException {
String personName = "testName";
Cgeneric<PersonInfo> generic = createCGenericPersonInfo(personName);
Object o = JSON.toJSON(generic);
{
Cgeneric personInfo = (Cgeneric) PojoUtils.realize(o, Cgeneric.class);
assertEquals(Cgeneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
assertTrue(personInfo.getA().getData() instanceof Map);
assertTrue(personInfo.getB().getData() instanceof PersonInfo);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createCGenericPersonInfo", String.class));
Cgeneric personInfo =
(Cgeneric) PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Cgeneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) personInfo.getData()).getName());
assertEquals(personInfo.getA().getClass(), Ageneric.class);
assertEquals(personInfo.getA().getData().getClass(), PersonInfo.class);
assertEquals(personInfo.getB().getClass(), Bgeneric.class);
assertEquals(personInfo.getB().getData().getClass(), PersonInfo.class);
}
}
protected Dgeneric<Ageneric<PersonInfo>, Bgeneric<PersonInfo>, Cgeneric<PersonInfo>> createDGenericPersonInfo(
String name) {
Dgeneric<Ageneric<PersonInfo>, Bgeneric<PersonInfo>, Cgeneric<PersonInfo>> ret = new Dgeneric();
ret.setT(createAGenericPersonInfo(name));
ret.setY(createBGenericPersonInfo(name));
ret.setZ(createCGenericPersonInfo(name));
return ret;
}
@Test
public void testPojoGeneric4() throws NoSuchMethodException {
String personName = "testName";
Dgeneric generic = createDGenericPersonInfo(personName);
Object o = JSON.toJSON(generic);
{
Dgeneric personInfo = (Dgeneric) PojoUtils.realize(o, Dgeneric.class);
assertEquals(Dgeneric.NAME, personInfo.getName());
assertTrue(personInfo.getT() instanceof Map);
assertTrue(personInfo.getY() instanceof Map);
assertTrue(personInfo.getZ() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createDGenericPersonInfo", String.class));
Dgeneric personInfo =
(Dgeneric) PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Dgeneric.NAME, personInfo.getName());
assertEquals(personInfo.getT().getClass(), Ageneric.class);
assertEquals(((Ageneric) personInfo.getT()).getData().getClass(), PersonInfo.class);
assertEquals(personInfo.getY().getClass(), Bgeneric.class);
assertEquals(((Bgeneric) personInfo.getY()).getData().getClass(), PersonInfo.class);
assertEquals(personInfo.getZ().getClass(), Cgeneric.class);
assertEquals(((Cgeneric) personInfo.getZ()).getData().getClass(), PersonInfo.class);
assertEquals(personInfo.getZ().getClass(), Cgeneric.class);
assertEquals(((Cgeneric) personInfo.getZ()).getA().getClass(), Ageneric.class);
assertEquals(((Cgeneric) personInfo.getZ()).getA().getData().getClass(), PersonInfo.class);
assertEquals(((Cgeneric) personInfo.getZ()).getB().getClass(), Bgeneric.class);
assertEquals(((Cgeneric) personInfo.getZ()).getB().getData().getClass(), PersonInfo.class);
}
}
@Test
void testNameNotMatch() {
NameNotMatch origin = new NameNotMatch();
origin.setNameA("test123");
origin.setNameB("test234");
Object generalized = PojoUtils.generalize(origin);
Assertions.assertInstanceOf(Map.class, generalized);
Assertions.assertEquals("test123", ((Map) generalized).get("nameA"));
Assertions.assertEquals("test234", ((Map) generalized).get("nameB"));
NameNotMatch target1 =
(NameNotMatch) PojoUtils.realize(PojoUtils.generalize(origin), NameNotMatch.class, NameNotMatch.class);
Assertions.assertEquals(origin, target1);
Map<String, String> map = new HashMap<>();
map.put("nameA", "test123");
map.put("nameB", "test234");
NameNotMatch target2 = (NameNotMatch) PojoUtils.realize(map, NameNotMatch.class, NameNotMatch.class);
Assertions.assertEquals(origin, target2);
}
class NameNotMatch implements Serializable {
private String NameA;
private String NameAbsent;
public void setNameA(String nameA) {
this.NameA = nameA;
}
public String getNameA() {
return NameA;
}
public void setNameB(String nameB) {
this.NameAbsent = nameB;
}
public String getNameB() {
return NameAbsent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NameNotMatch that = (NameNotMatch) o;
return Objects.equals(NameA, that.NameA) && Objects.equals(NameAbsent, that.NameAbsent);
}
@Override
public int hashCode() {
return Objects.hash(NameA, NameAbsent);
}
}
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
public static class BasicTestData implements Serializable {
public boolean a;
public char b;
public byte c;
public short d;
public int e;
public long f;
public float g;
public double h;
public BasicTestData(boolean a, char b, byte c, short d, int e, long f, float g, double h) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
this.g = g;
this.h = h;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (a ? 1 : 2);
result = prime * result + b;
result = prime * result + c;
result = prime * result + c;
result = prime * result + e;
result = (int) (prime * result + f);
result = (int) (prime * result + g);
result = (int) (prime * result + h);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BasicTestData other = (BasicTestData) obj;
if (a != other.a) {
return false;
}
if (b != other.b) {
return false;
}
if (c != other.c) {
return false;
}
if (e != other.e) {
return false;
}
if (f != other.f) {
return false;
}
if (g != other.g) {
return false;
}
if (h != other.h) {
return false;
}
return true;
}
}
public static class Parent implements Serializable {
public String gender;
public String email;
String name;
int age;
Child child;
private String securityEmail;
public static Parent getNewParent() {
return new Parent();
}
public String getEmail() {
return this.securityEmail;
}
public void setEmail(String email) {
this.securityEmail = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
public static class Child implements Serializable {
public String gender;
public int age;
String toy;
Parent parent;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getToy() {
return toy;
}
public void setToy(String toy) {
this.toy = toy;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
public static class TestData implements Serializable {
private Map<String, Child> children = new HashMap<String, Child>();
private List<Child> list = new ArrayList<Child>();
public List<Child> getList() {
return list;
}
public void setList(List<Child> list) {
if (CollectionUtils.isNotEmpty(list)) {
this.list.addAll(list);
}
}
public Map<String, Child> getChildren() {
return children;
}
public void setChildren(Map<String, Child> children) {
if (CollectionUtils.isNotEmptyMap(children)) {
this.children.putAll(children);
}
}
public void addChild(Child child) {
this.children.put(child.getName(), child);
}
}
public static class InnerPojo<T> implements Serializable {
private List<T> list;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
public static class ListResult<T> implements Serializable {
List<T> result;
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
}
interface Message {
String getContent();
String getFrom();
boolean isUrgent();
}
}
| 6,492 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.config.CompositeConfiguration;
import org.apache.dubbo.common.config.InmemoryConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ConfigUtilsTest {
private Properties properties;
@BeforeEach
public void setUp() throws Exception {
properties = ConfigUtils.getProperties(Collections.emptySet());
}
@AfterEach
public void tearDown() throws Exception {}
@Test
void testIsNotEmpty() throws Exception {
assertThat(ConfigUtils.isNotEmpty("abc"), is(true));
}
@Test
void testIsEmpty() throws Exception {
assertThat(ConfigUtils.isEmpty(null), is(true));
assertThat(ConfigUtils.isEmpty(""), is(true));
assertThat(ConfigUtils.isEmpty("false"), is(true));
assertThat(ConfigUtils.isEmpty("FALSE"), is(true));
assertThat(ConfigUtils.isEmpty("0"), is(true));
assertThat(ConfigUtils.isEmpty("null"), is(true));
assertThat(ConfigUtils.isEmpty("NULL"), is(true));
assertThat(ConfigUtils.isEmpty("n/a"), is(true));
assertThat(ConfigUtils.isEmpty("N/A"), is(true));
}
@Test
void testIsDefault() throws Exception {
assertThat(ConfigUtils.isDefault("true"), is(true));
assertThat(ConfigUtils.isDefault("TRUE"), is(true));
assertThat(ConfigUtils.isDefault("default"), is(true));
assertThat(ConfigUtils.isDefault("DEFAULT"), is(true));
}
@Test
void testMergeValues() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"aaa,bbb,default.custom",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("fixed", "cached", "aaa", "bbb", "default.custom"), merged);
}
@Test
void testMergeValuesAddDefault() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"aaa,bbb,default,zzz",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("aaa", "bbb", "fixed", "cached", "zzz"), merged);
}
@Test
void testMergeValuesDeleteDefault() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-default",
asList("fixed", "default.limited", "cached"));
assertEquals(Collections.emptyList(), merged);
}
@Test
void testMergeValuesDeleteDefault_2() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-default,aaa",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("aaa"), merged);
}
/**
* The user configures -default, which will delete all the default parameters
*/
@Test
void testMergeValuesDelete() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-fixed,aaa",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("cached", "aaa"), merged);
}
@Test
void testReplaceProperty() throws Exception {
String s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.singletonMap("a.b.c", "ABC"));
assertEquals("1ABC2ABC3", s);
s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.<String, String>emptyMap());
assertEquals("1${a.b.c}2${a.b.c}3", s);
}
@Test
void testReplaceProperty2() {
InmemoryConfiguration configuration1 = new InmemoryConfiguration();
configuration1.getProperties().put("zookeeper.address", "127.0.0.1");
InmemoryConfiguration configuration2 = new InmemoryConfiguration();
configuration2.getProperties().put("zookeeper.port", "2181");
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(configuration1);
compositeConfiguration.addConfiguration(configuration2);
String s = ConfigUtils.replaceProperty(
"zookeeper://${zookeeper.address}:${zookeeper.port}", compositeConfiguration);
assertEquals("zookeeper://127.0.0.1:2181", s);
// should not replace inner class name
String interfaceName = "dubbo.service.io.grpc.examples.helloworld.DubboGreeterGrpc$IGreeter";
s = ConfigUtils.replaceProperty(interfaceName, compositeConfiguration);
Assertions.assertEquals(interfaceName, s);
}
@Test
void testGetProperties1() throws Exception {
try {
System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, "properties.load");
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("a"), equalTo("12"));
assertThat((String) p.get("b"), equalTo("34"));
assertThat((String) p.get("c"), equalTo("56"));
} finally {
System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
}
}
@Test
void testGetProperties2() throws Exception {
System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesNoFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", true);
Properties expected = new Properties();
assertEquals(expected, p);
p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", false);
assertEquals(expected, p);
}
@Test
void testGetProperty() throws Exception {
assertThat(properties.getProperty("dubbo"), equalTo("properties"));
}
@Test
void testGetPropertyDefaultValue() throws Exception {
assertThat(properties.getProperty("not-exist", "default"), equalTo("default"));
}
@Test
void testGetSystemProperty() throws Exception {
try {
System.setProperty("dubbo", "system-only");
assertThat(ConfigUtils.getSystemProperty("dubbo"), equalTo("system-only"));
} finally {
System.clearProperty("dubbo");
}
}
@Test
void testLoadProperties() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "dubbo.properties");
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesOneFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", false);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileAllowMulti() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", true);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileNotRootPath() throws Exception {
Properties p = ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool", false);
Properties expected = new Properties();
expected.put("fixed", "org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool");
expected.put("cached", "org.apache.dubbo.common.threadpool.support.cached.CachedThreadPool");
expected.put("limited", "org.apache.dubbo.common.threadpool.support.limited.LimitedThreadPool");
expected.put("eager", "org.apache.dubbo.common.threadpool.support.eager.EagerThreadPool");
assertEquals(expected, p);
}
@Disabled("Not know why disabled, the original link explaining this was reachable.")
@Test
void testLoadPropertiesMultiFileNotRootPathException() throws Exception {
try {
ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/services/org.apache.dubbo.common.status.StatusChecker", false);
Assertions.fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"only 1 META-INF/services/org.apache.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:"));
}
}
@Test
void testLoadPropertiesMultiFileNotRootPath() throws Exception {
Properties p = ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker", true);
Properties expected = new Properties();
expected.put("memory", "org.apache.dubbo.common.status.support.MemoryStatusChecker");
expected.put("load", "org.apache.dubbo.common.status.support.LoadStatusChecker");
expected.put("aa", "12");
assertEquals(expected, p);
}
@Test
void testGetPid() throws Exception {
assertThat(ConfigUtils.getPid(), greaterThan(0));
}
@Test
void testPropertiesWithStructedValue() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "parameters.properties", false);
Properties expected = new Properties();
expected.put("dubbo.parameters", "[{a:b},{c_.d: r*}]");
assertEquals(expected, p);
}
@Test
void testLoadMigrationRule() {
Set<ClassLoader> classLoaderSet = new HashSet<>();
classLoaderSet.add(ClassUtils.getClassLoader());
String rule = ConfigUtils.loadMigrationRule(classLoaderSet, "dubbo-migration.yaml");
Assertions.assertNotNull(rule);
}
}
| 6,493 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TimeUtilsTest {
@Test
void testCurrentTimeMillis() {
assertTrue(0 < TimeUtils.currentTimeMillis());
}
}
| 6,494 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public class TestObjectA {
private String name;
private int age;
private TestEnum testEnum;
public TestObjectA() {}
public TestObjectA(String name, int age, TestEnum testEnum) {
this.name = name;
this.age = age;
this.testEnum = testEnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public TestEnum getTestEnum() {
return testEnum;
}
public void setTestEnum(TestEnum testEnum) {
this.testEnum = testEnum;
}
}
| 6,495 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public enum TestEnum {
TYPE_A,
TYPE_B,
TYPE_C
}
| 6,496 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public class TestObjectB {
private Inner innerA;
private Inner innerB;
public Inner getInnerA() {
return innerA;
}
public void setInnerA(Inner innerA) {
this.innerA = innerA;
}
public Inner getInnerB() {
return innerB;
}
public void setInnerB(Inner innerB) {
this.innerB = innerB;
}
public static class Inner {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| 6,497 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.status.Status.Level.OK;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
class StatusTest {
@Test
void testConstructor1() throws Exception {
Status status = new Status(OK, "message", "description");
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), equalTo("message"));
assertThat(status.getDescription(), equalTo("description"));
}
@Test
void testConstructor2() throws Exception {
Status status = new Status(OK, "message");
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), equalTo("message"));
assertThat(status.getDescription(), isEmptyOrNullString());
}
@Test
void testConstructor3() throws Exception {
Status status = new Status(OK);
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), isEmptyOrNullString());
assertThat(status.getDescription(), isEmptyOrNullString());
}
}
| 6,498 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/MockFrameworkStatusReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.reporter;
import java.util.HashMap;
import java.util.Map;
public class MockFrameworkStatusReporter implements FrameworkStatusReporter {
Map<String, Object> reportContent = new HashMap<>();
@Override
public void report(String type, Object obj) {
reportContent.put(type, obj);
}
public Map<String, Object> getReportContent() {
return reportContent;
}
}
| 6,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.