repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class StickyTest {
private List<Invoker<StickyTest>> invokers = new ArrayList<Invoker<StickyTest>>();
private Invoker<StickyTest> invoker1 = mock(Invoker.class);
private Invoker<StickyTest> invoker2 = mock(Invoker.class);
private RpcInvocation invocation;
private Directory<StickyTest> dic;
private Result result = new AppResponse();
private StickyClusterInvoker<StickyTest> clusterinvoker = null;
private URL url =
URL.valueOf("test://test:11/test?" + "&loadbalance=roundrobin" + "&" + CLUSTER_STICKY_KEY + "=true");
private int runs = 1;
@BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
invocation = new RpcInvocation();
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(StickyTest.class);
invokers.add(invoker1);
invokers.add(invoker2);
clusterinvoker = new StickyClusterInvoker<StickyTest>(dic);
}
@Test
void testStickyNoCheck() {
int count = testSticky("t1", false);
Assertions.assertTrue(count > 0 && count <= runs);
}
@Test
void testStickyForceCheck() {
int count = testSticky("t2", true);
Assertions.assertTrue(count == 0 || count == runs);
}
@Test
void testMethodStickyNoCheck() {
int count = testSticky("method1", false);
Assertions.assertTrue(count > 0 && count <= runs);
}
@Test
void testMethodStickyForceCheck() {
int count = testSticky("method1", true);
Assertions.assertTrue(count == 0 || count == runs);
}
@Test
void testMethodsSticky() {
for (int i = 0; i < 100; i++) { // Two different methods should always use the same invoker every time.
int count1 = testSticky("method1", true);
int count2 = testSticky("method2", true);
Assertions.assertEquals(count1, count2);
}
}
public int testSticky(String methodName, boolean check) {
if (methodName == null) {
url = url.addParameter(CLUSTER_STICKY_KEY, String.valueOf(check));
} else {
url = url.addParameter(methodName + "." + CLUSTER_STICKY_KEY, String.valueOf(check));
}
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getUrl()).willReturn(url.setPort(1));
given(invoker1.getInterface()).willReturn(StickyTest.class);
given(invoker2.invoke(invocation)).willReturn(result);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getUrl()).willReturn(url.setPort(2));
given(invoker2.getInterface()).willReturn(StickyTest.class);
invocation.setMethodName(methodName);
int count = 0;
for (int i = 0; i < runs; i++) {
Assertions.assertNull(clusterinvoker.invoke(invocation));
if (invoker1 == clusterinvoker.getSelectedInvoker()) {
count++;
}
}
return count;
}
static class StickyClusterInvoker<T> extends AbstractClusterInvoker<T> {
private Invoker<T> selectedInvoker;
public StickyClusterInvoker(Directory<T> directory) {
super(directory);
}
public StickyClusterInvoker(Directory<T> directory, URL url) {
super(directory, url);
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
selectedInvoker = invoker;
return null;
}
public Invoker<T> getSelectedInvoker() {
return selectedInvoker;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator;
import org.apache.dubbo.rpc.cluster.configurator.override.OverrideConfigurator;
import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link Configurator}
*/
class ConfiguratorTest {
@Test
void test() {
Optional<List<Configurator>> emptyOptional = Configurator.toConfigurators(Collections.emptyList());
Assertions.assertEquals(Optional.empty(), emptyOptional);
String configData =
"[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=2&version=1.0\""
+ ", \"absent://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]";
List<URL> urls = ConfigParser.parseConfigurators(configData);
Optional<List<Configurator>> optionalList = Configurator.toConfigurators(urls);
Assertions.assertTrue(optionalList.isPresent());
List<Configurator> configurators = optionalList.get();
Assertions.assertEquals(configurators.size(), 2);
// The hosts of AbsentConfigurator and OverrideConfigurator are equal, but the priority of OverrideConfigurator
// is higher
Assertions.assertTrue(configurators.get(0) instanceof AbsentConfigurator);
Assertions.assertTrue(configurators.get(1) instanceof OverrideConfigurator);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class ForkingClusterInvokerTest {
private List<Invoker<ForkingClusterInvokerTest>> invokers = new ArrayList<>();
private URL url = URL.valueOf("test://test:11/test?forks=2");
private Invoker<ForkingClusterInvokerTest> invoker1 = mock(Invoker.class);
private Invoker<ForkingClusterInvokerTest> invoker2 = mock(Invoker.class);
private Invoker<ForkingClusterInvokerTest> invoker3 = mock(Invoker.class);
private RpcInvocation invocation = new RpcInvocation();
private Directory<ForkingClusterInvokerTest> dic;
private Result result = new AppResponse();
@BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(ForkingClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
}
private void resetInvokerToException() {
given(invoker1.invoke(invocation)).willThrow(new RuntimeException());
given(invoker1.getUrl()).willReturn(url);
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willThrow(new RuntimeException());
given(invoker2.getUrl()).willReturn(url);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class);
given(invoker3.invoke(invocation)).willThrow(new RuntimeException());
given(invoker3.getUrl()).willReturn(url);
given(invoker3.isAvailable()).willReturn(true);
given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class);
}
private void resetInvokerToNoException() {
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willReturn(result);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class);
given(invoker3.invoke(invocation)).willReturn(result);
given(invoker3.getUrl()).willReturn(url);
given(invoker3.isAvailable()).willReturn(true);
given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class);
}
@Test
void testInvokeException() {
resetInvokerToException();
ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
Assertions.fail();
} catch (RpcException expected) {
Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"));
assertFalse(expected.getCause() instanceof RpcException);
}
}
@Test
void testClearRpcContext() {
resetInvokerToException();
ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic);
String attachKey = "attach";
String attachValue = "value";
RpcContext.getClientAttachment().setAttachment(attachKey, attachValue);
Map<String, Object> attachments = RpcContext.getClientAttachment().getObjectAttachments();
Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!");
try {
invoker.invoke(invocation);
Assertions.fail();
} catch (RpcException expected) {
Assertions.assertTrue(
expected.getMessage().contains("Failed to forking invoke provider"),
"Succeeded to forking invoke provider !");
assertFalse(expected.getCause() instanceof RpcException);
}
Map<String, Object> afterInvoke = RpcContext.getClientAttachment().getObjectAttachments();
Assertions.assertTrue(afterInvoke != null && afterInvoke.size() == 0, "clear attachment failed!");
}
@Test
void testInvokeNoException() {
resetInvokerToNoException();
ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic);
Result ret = invoker.invoke(invocation);
Assertions.assertSame(result, ret);
}
@Test
void testInvokeWithIllegalForksParam() {
URL url = URL.valueOf("test://test:11/test?forks=-1");
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class);
ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic);
Result ret = invoker.invoke(invocation);
Assertions.assertSame(result, ret);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.SingleRouterChain;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.protocol.AbstractInvoker;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class FailoverClusterInvokerTest {
private final int retries = 5;
private final URL url = URL.valueOf("test://test:11/test?retries=" + retries);
private final Invoker<FailoverClusterInvokerTest> invoker1 = mock(Invoker.class);
private final Invoker<FailoverClusterInvokerTest> invoker2 = mock(Invoker.class);
private final RpcInvocation invocation = new RpcInvocation();
private final Result expectedResult = new AppResponse();
private final List<Invoker<FailoverClusterInvokerTest>> invokers = new ArrayList<>();
private Directory<FailoverClusterInvokerTest> dic;
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(FailoverClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
invokers.add(invoker2);
}
@Test
void testInvokeWithRuntimeException() {
given(invoker1.invoke(invocation)).willThrow(new RuntimeException());
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willThrow(new RuntimeException());
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
fail();
} catch (RpcException actualException) {
assertEquals(0, actualException.getCode());
assertFalse(actualException.getCause() instanceof RpcException);
}
}
@Test
void testInvokeWithRPCException() {
given(invoker1.invoke(invocation)).willThrow(new RpcException());
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willReturn(expectedResult);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
for (int i = 0; i < 100; i++) {
Result actualResult = invoker.invoke(invocation);
assertSame(expectedResult, actualResult);
}
}
@Test
void testInvoke_retryTimes() {
given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION));
given(invoker1.isAvailable()).willReturn(false);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willThrow(new RpcException());
given(invoker2.isAvailable()).willReturn(false);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
try {
Result actualResult = invoker.invoke(invocation);
assertSame(expectedResult, actualResult);
fail();
} catch (RpcException actualException) {
assertTrue((actualException.isTimeout() || actualException.getCode() == 0));
assertTrue(actualException.getMessage().indexOf((retries + 1) + " times") > 0);
}
}
@Test
void testInvoke_retryTimes2() {
int finalRetries = 1;
given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION));
given(invoker1.isAvailable()).willReturn(false);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willThrow(new RpcException());
given(invoker2.isAvailable()).willReturn(false);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);
RpcContext rpcContext = RpcContext.getContext();
rpcContext.setAttachment("retries", finalRetries);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
try {
Result actualResult = invoker.invoke(invocation);
assertSame(expectedResult, actualResult);
fail();
} catch (RpcException actualException) {
assertTrue((actualException.isTimeout() || actualException.getCode() == 0));
assertTrue(actualException.getMessage().indexOf((finalRetries + 1) + " times") > 0);
}
}
@Test
void testInvoke_retryTimes_withBizException() {
given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION));
given(invoker1.isAvailable()).willReturn(false);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION));
given(invoker2.isAvailable()).willReturn(false);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
try {
Result actualResult = invoker.invoke(invocation);
assertSame(expectedResult, actualResult);
fail();
} catch (RpcException actualException) {
assertEquals(RpcException.BIZ_EXCEPTION, actualException.getCode());
}
}
@Test
void testInvoke_without_retry() {
int withoutRetry = 0;
final URL url = URL.valueOf(
"test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + withoutRetry);
RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION);
MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url);
invoker1.setException(exception);
MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url);
invoker2.setException(exception);
final List<Invoker<Demo>> invokers = new ArrayList<>();
invokers.add(invoker1);
invokers.add(invoker2);
try {
Directory<Demo> dic = new MockDirectory<>(url, invokers);
FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic);
RpcInvocation inv = new RpcInvocation();
inv.setMethodName("test");
clusterInvoker.invoke(inv);
} catch (RpcException actualException) {
assertTrue(actualException.getCause() instanceof RpcException);
assertEquals(RpcException.TIMEOUT_EXCEPTION, actualException.getCode());
}
}
@Test
void testInvoke_when_retry_illegal() {
int illegalRetry = -1;
final URL url = URL.valueOf(
"test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + illegalRetry);
RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION);
MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url);
invoker1.setException(exception);
MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url);
invoker2.setException(exception);
final List<Invoker<Demo>> invokers = new ArrayList<>();
invokers.add(invoker1);
invokers.add(invoker2);
try {
Directory<Demo> dic = new MockDirectory<>(url, invokers);
FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic);
RpcInvocation inv = new RpcInvocation();
inv.setMethodName("test");
clusterInvoker.invoke(inv);
} catch (RpcException actualException) {
assertTrue(actualException.getCause() instanceof RpcException);
assertEquals(RpcException.TIMEOUT_EXCEPTION, actualException.getCode());
}
}
@Test
void testNoInvoke() {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(null);
given(dic.getInterface()).willReturn(FailoverClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
fail();
} catch (RpcException actualException) {
assertFalse(actualException.getCause() instanceof RpcException);
}
}
/**
* When invokers in directory changes after a failed request but just before a retry effort,
* then we should reselect from the latest invokers before retry.
*/
@Test
void testInvokerDestroyAndReList() {
final URL url =
URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + retries);
RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION);
MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url);
invoker1.setException(exception);
MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url);
invoker2.setException(exception);
final List<Invoker<Demo>> invokers = new ArrayList<>();
invokers.add(invoker1);
invokers.add(invoker2);
MockDirectory<Demo> dic = new MockDirectory<>(url, invokers);
Callable<Object> callable = () -> {
// Simulation: all invokers are destroyed
for (Invoker<Demo> invoker : invokers) {
invoker.destroy();
}
invokers.clear();
MockInvoker<Demo> invoker3 = new MockInvoker<>(Demo.class, url);
invoker3.setResult(AsyncRpcResult.newDefaultAsyncResult(mock(RpcInvocation.class)));
invokers.add(invoker3);
dic.notify(invokers);
return null;
};
invoker1.setCallable(callable);
invoker2.setCallable(callable);
RpcInvocation inv = new RpcInvocation();
inv.setMethodName("test");
FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic);
clusterInvoker.invoke(inv);
}
public interface Demo {}
public static class MockInvoker<T> extends AbstractInvoker<T> {
URL url;
boolean available = true;
boolean destroyed = false;
Result result;
RpcException exception;
Callable<?> callable;
public MockInvoker(Class<T> type, URL url) {
super(type, url);
}
public void setResult(Result result) {
this.result = result;
}
public void setException(RpcException exception) {
this.exception = exception;
}
public void setCallable(Callable<?> callable) {
this.callable = callable;
}
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
if (callable != null) {
try {
callable.call();
} catch (Exception e) {
throw new RpcException(e);
}
}
if (exception != null) {
throw exception;
} else {
return result;
}
}
}
public static class MockDirectory<T> extends StaticDirectory<T> {
public MockDirectory(URL url, List<Invoker<T>> invokers) {
super(url, invokers);
}
@Override
protected List<Invoker<T>> doList(
SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation)
throws RpcException {
return super.doList(singleRouterChain, invokers, invocation);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceB.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceB.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.rpc.cluster.support;
public interface DemoServiceB {
String methodB();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* FailfastClusterInvokerTest
*
*/
@SuppressWarnings("unchecked")
class FailSafeClusterInvokerTest {
List<Invoker<DemoService>> invokers = new ArrayList<Invoker<DemoService>>();
URL url = URL.valueOf("test://test:11/test");
Invoker<DemoService> invoker = mock(Invoker.class);
RpcInvocation invocation = new RpcInvocation();
Directory<DemoService> dic;
Result result = new AppResponse();
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
RpcContext.removeServiceContext();
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(DemoService.class);
invocation.setMethodName("method1");
invokers.add(invoker);
}
private void resetInvokerToException() {
given(invoker.invoke(invocation)).willThrow(new RuntimeException());
given(invoker.getUrl()).willReturn(url);
given(invoker.getInterface()).willReturn(DemoService.class);
}
private void resetInvokerToNoException() {
given(invoker.invoke(invocation)).willReturn(result);
given(invoker.getUrl()).willReturn(url);
given(invoker.getInterface()).willReturn(DemoService.class);
}
// TODO assert error log
@Test
void testInvokeException() {
resetInvokerToException();
FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
invoker.invoke(invocation);
Assertions.assertNull(RpcContext.getServiceContext().getInvoker());
}
@Test
void testInvokeNoException() {
resetInvokerToNoException();
FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
Result ret = invoker.invoke(invocation);
Assertions.assertSame(result, ret);
}
@Test
void testNoInvoke() {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(null);
given(dic.getInterface()).willReturn(DemoService.class);
invocation.setMethodName("method1");
resetInvokerToNoException();
FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
try {
invoker.invoke(invocation);
} catch (RpcException e) {
Assertions.assertTrue(e.getMessage().contains("No provider available"));
assertFalse(e.getCause() instanceof RpcException);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.rpc.Constants.MERGER_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class MergeableClusterInvokerTest {
private Directory directory = mock(Directory.class);
private Invoker firstInvoker = mock(Invoker.class);
private Invoker secondInvoker = mock(Invoker.class);
private Invocation invocation = mock(RpcInvocation.class);
private ModuleModel moduleModel = mock(ModuleModel.class);
private MergeableClusterInvoker<MenuService> mergeableClusterInvoker;
private String[] list1 = {"10", "11", "12"};
private String[] list2 = {"20", "21", "22"};
private final Map<String, List<String>> firstMenuMap = new HashMap<String, List<String>>() {
{
put("1", Arrays.asList(list1));
put("2", Arrays.asList(list2));
}
};
private final Menu firstMenu = new Menu(firstMenuMap);
private String[] list3 = {"23", "24", "25"};
private String[] list4 = {"30", "31", "32"};
private final Map<String, List<String>> secondMenuMap = new HashMap<String, List<String>>() {
{
put("2", Arrays.asList(list3));
put("3", Arrays.asList(list4));
}
};
private final Menu secondMenu = new Menu(secondMenuMap);
private URL url = URL.valueOf("test://test/" + MenuService.class.getName());
static void merge(Map<String, List<String>> first, Map<String, List<String>> second) {
for (Map.Entry<String, List<String>> entry : second.entrySet()) {
List<String> value = first.get(entry.getKey());
if (value != null) {
value.addAll(entry.getValue());
} else {
first.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
}
}
@BeforeEach
public void setUp() throws Exception {
directory = mock(Directory.class);
firstInvoker = mock(Invoker.class);
secondInvoker = mock(Invoker.class);
invocation = mock(RpcInvocation.class);
}
@Test
void testGetMenuSuccessfully() {
// setup
url = url.addParameter(MERGER_KEY, ".merge");
given(invocation.getMethodName()).willReturn("getMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
firstInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "first");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation);
}
return null;
});
secondInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "second");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation);
}
return null;
});
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
// invoke
Result result = mergeableClusterInvoker.invoke(invocation);
assertTrue(result.getValue() instanceof Menu);
Menu menu = (Menu) result.getValue();
Map<String, List<String>> expected = new HashMap<>();
merge(expected, firstMenuMap);
merge(expected, secondMenuMap);
assertEquals(expected.keySet(), menu.getMenus().keySet());
for (Map.Entry<String, List<String>> entry : expected.entrySet()) {
// FIXME: cannot guarantee the sequence of the merge result, check implementation in
// MergeableClusterInvoker#invoke
List<String> values1 = new ArrayList<>(entry.getValue());
List<String> values2 = new ArrayList<>(menu.getMenus().get(entry.getKey()));
Collections.sort(values1);
Collections.sort(values2);
assertEquals(values1, values2);
}
}
@Test
void testAddMenu() {
String menu = "first";
List<String> menuItems = new ArrayList<String>() {
{
add("1");
add("2");
}
};
given(invocation.getMethodName()).willReturn("addMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class});
given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first"));
given(firstInvoker.getInterface()).willReturn(MenuService.class);
given(firstInvoker.invoke(invocation)).willReturn(new AppResponse());
given(firstInvoker.isAvailable()).willReturn(true);
given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second"));
given(secondInvoker.getInterface()).willReturn(MenuService.class);
given(secondInvoker.invoke(invocation)).willReturn(new AppResponse());
given(secondInvoker.isAvailable()).willReturn(true);
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
Result result = mergeableClusterInvoker.invoke(invocation);
Assertions.assertNull(result.getValue());
}
@Test
void testAddMenu1() {
// setup
url = url.addParameter(MERGER_KEY, ".merge");
String menu = "first";
List<String> menuItems = new ArrayList<String>() {
{
add("1");
add("2");
}
};
given(invocation.getMethodName()).willReturn("addMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class});
given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
firstInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "first");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation);
}
return null;
});
secondInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "second");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation);
}
return null;
});
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
Result result = mergeableClusterInvoker.invoke(invocation);
Assertions.assertNull(result.getValue());
}
@Test
void testInvokerToNoInvokerAvailableException() {
String menu = "first";
List<String> menuItems = new ArrayList<String>() {
{
add("1");
add("2");
}
};
given(invocation.getMethodName()).willReturn("addMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class});
given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first"));
given(firstInvoker.getInterface()).willReturn(MenuService.class);
given(firstInvoker.invoke(invocation)).willReturn(new AppResponse());
given(firstInvoker.isAvailable()).willReturn(true);
given(firstInvoker.invoke(invocation))
.willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER));
given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second"));
given(secondInvoker.getInterface()).willReturn(MenuService.class);
given(secondInvoker.invoke(invocation)).willReturn(new AppResponse());
given(secondInvoker.isAvailable()).willReturn(true);
given(secondInvoker.invoke(invocation))
.willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER));
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
// invoke
try {
Result result = mergeableClusterInvoker.invoke(invocation);
fail();
Assertions.assertNull(result.getValue());
} catch (RpcException expected) {
assertEquals(expected.getCode(), RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER);
}
}
/**
* test when network exception
*/
@Test
void testInvokerToException() {
String menu = "first";
List<String> menuItems = new ArrayList<String>() {
{
add("1");
add("2");
}
};
given(invocation.getMethodName()).willReturn("addMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class});
given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first"));
given(firstInvoker.getInterface()).willReturn(MenuService.class);
given(firstInvoker.invoke(invocation)).willReturn(new AppResponse());
given(firstInvoker.isAvailable()).willReturn(true);
given(firstInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NETWORK_EXCEPTION));
given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second"));
given(secondInvoker.getInterface()).willReturn(MenuService.class);
given(secondInvoker.invoke(invocation)).willReturn(new AppResponse());
given(secondInvoker.isAvailable()).willReturn(true);
given(secondInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NETWORK_EXCEPTION));
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
// invoke
try {
Result result = mergeableClusterInvoker.invoke(invocation);
fail();
Assertions.assertNull(result.getValue());
} catch (RpcException expected) {
assertEquals(expected.getCode(), RpcException.NETWORK_EXCEPTION);
}
}
@Test
void testGetMenuResultHasException() {
// setup
url = url.addParameter(MERGER_KEY, ".merge");
given(invocation.getMethodName()).willReturn("getMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first"));
given(firstInvoker.getInterface()).willReturn(MenuService.class);
given(firstInvoker.invoke(invocation)).willReturn(new AppResponse());
given(firstInvoker.isAvailable()).willReturn(true);
given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second"));
given(secondInvoker.getInterface()).willReturn(MenuService.class);
given(secondInvoker.invoke(invocation)).willReturn(new AppResponse());
given(secondInvoker.isAvailable()).willReturn(true);
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
// invoke
try {
Result result = mergeableClusterInvoker.invoke(invocation);
fail();
Assertions.assertNull(result.getValue());
} catch (RpcException expected) {
Assertions.assertTrue(expected.getMessage().contains("Failed to invoke service"));
}
}
@Test
void testGetMenuWithMergerDefault() {
// setup
url = url.addParameter(MERGER_KEY, "default");
given(invocation.getMethodName()).willReturn("getMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
// mock ApplicationModel
given(invocation.getModuleModel()).willReturn(moduleModel);
given(invocation.getModuleModel().getApplicationModel()).willReturn(ApplicationModel.defaultModel());
firstInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "first");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation);
}
return null;
});
secondInvoker = (Invoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url.addParameter(GROUP_KEY, "second");
}
if ("getInterface".equals(method.getName())) {
return MenuService.class;
}
if ("invoke".equals(method.getName())) {
return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation);
}
return null;
});
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
// invoke
try {
mergeableClusterInvoker.invoke(invocation);
} catch (RpcException exception) {
Assertions.assertTrue(exception.getMessage().contains("There is no merger to merge result."));
}
}
@Test
void testDestroy() {
given(invocation.getMethodName()).willReturn("getMenu");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
given(invocation.getInvoker()).willReturn(firstInvoker);
given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first"));
given(firstInvoker.getInterface()).willReturn(MenuService.class);
given(firstInvoker.invoke(invocation)).willReturn(new AppResponse());
given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second"));
given(secondInvoker.getInterface()).willReturn(MenuService.class);
given(secondInvoker.invoke(invocation)).willReturn(new AppResponse());
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.getInterface()).willReturn(MenuService.class);
mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory);
mergeableClusterInvoker.destroy();
assertFalse(firstInvoker.isAvailable());
assertFalse(secondInvoker.isAvailable());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* AbstractClusterInvokerTest
*/
@SuppressWarnings("rawtypes")
class MockAbstractClusterInvokerTest {
List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>();
List<Invoker<IHelloService>> selectedInvokers = new ArrayList<Invoker<IHelloService>>();
AbstractClusterInvoker<IHelloService> cluster;
AbstractClusterInvoker<IHelloService> cluster_nocheck;
StaticDirectory<IHelloService> dic;
RpcInvocation invocation = new RpcInvocation();
URL url = URL.valueOf(
"registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer="
+ URL.encode("application=abstractClusterInvokerTest"));
URL consumerUrl = URL.valueOf(
"dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest");
Invoker<IHelloService> invoker1;
Invoker<IHelloService> invoker2;
Invoker<IHelloService> invoker3;
Invoker<IHelloService> invoker4;
Invoker<IHelloService> invoker5;
Invoker<IHelloService> mockedInvoker1;
@BeforeAll
public static void setUpBeforeClass() throws Exception {
System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false");
}
@AfterEach
public void teardown() throws Exception {
RpcContext.removeContext();
}
@AfterAll
public static void afterClass() {
System.clearProperty(ENABLE_CONNECTIVITY_VALIDATION);
}
@SuppressWarnings({"unchecked"})
@BeforeEach
public void setUp() throws Exception {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
Map<String, Object> attributes = new HashMap<>();
attributes.put("application", "abstractClusterInvokerTest");
url = url.putAttribute(REFER_KEY, attributes);
invocation.setMethodName("sayHello");
invoker1 = mock(Invoker.class);
invoker2 = mock(Invoker.class);
invoker3 = mock(Invoker.class);
invoker4 = mock(Invoker.class);
invoker5 = mock(Invoker.class);
mockedInvoker1 = mock(Invoker.class);
URL turl = URL.valueOf("test://test:11/test");
given(invoker1.isAvailable()).willReturn(false);
given(invoker1.getInterface()).willReturn(IHelloService.class);
given(invoker1.getUrl()).willReturn(turl.setPort(1).addParameter("name", "invoker1"));
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(IHelloService.class);
given(invoker2.getUrl()).willReturn(turl.setPort(2).addParameter("name", "invoker2"));
given(invoker3.isAvailable()).willReturn(false);
given(invoker3.getInterface()).willReturn(IHelloService.class);
given(invoker3.getUrl()).willReturn(turl.setPort(3).addParameter("name", "invoker3"));
given(invoker4.isAvailable()).willReturn(true);
given(invoker4.getInterface()).willReturn(IHelloService.class);
given(invoker4.getUrl()).willReturn(turl.setPort(4).addParameter("name", "invoker4"));
given(invoker5.isAvailable()).willReturn(false);
given(invoker5.getInterface()).willReturn(IHelloService.class);
given(invoker5.getUrl()).willReturn(turl.setPort(5).addParameter("name", "invoker5"));
given(mockedInvoker1.isAvailable()).willReturn(false);
given(mockedInvoker1.getInterface()).willReturn(IHelloService.class);
given(mockedInvoker1.getUrl()).willReturn(turl.setPort(999).setProtocol("mock"));
invokers.add(invoker1);
dic = new StaticDirectory<IHelloService>(url, invokers, null);
cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
};
cluster_nocheck =
new AbstractClusterInvoker(
dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
};
}
private void initlistsize5() {
invokers.clear();
selectedInvokers
.clear(); // Clear first, previous test case will make sure that the right invoker2 will be used.
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
invokers.add(invoker4);
invokers.add(invoker5);
}
private void initDic() {
dic.notify(invokers);
dic.buildRouterChain();
}
/**
* Test mock invoker selector works as expected
*/
@Test
void testMockedInvokerSelect() {
initlistsize5();
invokers.add(mockedInvoker1);
initDic();
RpcInvocation mockedInvocation = new RpcInvocation();
mockedInvocation.setMethodName("sayHello");
mockedInvocation.setAttachment(INVOCATION_NEED_MOCK, "true");
List<Invoker<IHelloService>> mockedInvokers = dic.list(mockedInvocation);
Assertions.assertEquals(1, mockedInvokers.size());
List<Invoker<IHelloService>> invokers = dic.list(invocation);
Assertions.assertEquals(5, invokers.size());
}
public static interface IHelloService {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceA.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceA.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.rpc.cluster.support;
public interface DemoServiceA {
String methodA();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.support.MockInvoker;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
class MockInvokerTest {
@Test
void testParseMockValue() throws Exception {
Assertions.assertNull(MockInvoker.parseMockValue("null"));
Assertions.assertNull(MockInvoker.parseMockValue("empty"));
Assertions.assertTrue((Boolean) MockInvoker.parseMockValue("true"));
Assertions.assertFalse((Boolean) MockInvoker.parseMockValue("false"));
Assertions.assertEquals(123, MockInvoker.parseMockValue("123"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("foo"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("\"foo\""));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("\'foo\'"));
Assertions.assertEquals(new HashMap<>(), MockInvoker.parseMockValue("{}"));
Assertions.assertEquals(new ArrayList<>(), MockInvoker.parseMockValue("[]"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("foo", new Type[] {String.class}));
}
@Test
void testInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "return ");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
}
@Test
void testGetDefaultObject() {
// test methodA in DemoServiceAMock
final Class<DemoServiceA> demoServiceAClass = DemoServiceA.class;
URL url = URL.valueOf("remote://1.2.3.4/" + demoServiceAClass.getName());
url = url.addParameter(MOCK_KEY, "force:true");
MockInvoker mockInvoker = new MockInvoker(url, demoServiceAClass);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("methodA");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
// test methodB in DemoServiceBMock
final Class<DemoServiceB> demoServiceBClass = DemoServiceB.class;
url = URL.valueOf("remote://1.2.3.4/" + demoServiceBClass.getName());
url = url.addParameter(MOCK_KEY, "force:true");
mockInvoker = new MockInvoker(url, demoServiceBClass);
invocation = new RpcInvocation();
invocation.setMethodName("methodB");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
}
@Test
void testInvokeThrowsRpcException1() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
MockInvoker mockInvoker = new MockInvoker(url, null);
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(new RpcInvocation()));
}
@Test
void testInvokeThrowsRpcException2() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "fail");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation));
}
@Test
void testInvokeThrowsRpcException3() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "throw");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation));
}
@Test
void testGetThrowable() {
Assertions.assertThrows(
RpcException.class, () -> org.apache.dubbo.rpc.support.MockInvoker.getThrowable("Exception.class"));
}
@Test
void testGetMockObject() {
Assertions.assertEquals(
"",
MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "true", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "default", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", Integer.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(),
"java.io.Serializable",
Serializable.class));
}
@Test
void testNormalizeMock() {
Assertions.assertNull(MockInvoker.normalizeMock(null));
Assertions.assertEquals("", MockInvoker.normalizeMock(""));
Assertions.assertEquals("", MockInvoker.normalizeMock("fail:"));
Assertions.assertEquals("", MockInvoker.normalizeMock("force:"));
Assertions.assertEquals("throw", MockInvoker.normalizeMock("throw"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("fail"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("force"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("true"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("default"));
Assertions.assertEquals("return null", MockInvoker.normalizeMock("return"));
Assertions.assertEquals("return null", MockInvoker.normalizeMock("return null"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceBMock.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceBMock.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.rpc.cluster.support;
/**
* default mock service for DemoServiceA
*/
public class DemoServiceBMock implements DemoServiceB {
public static final String MOCK_VALUE = "mockB";
@Override
public String methodB() {
return MOCK_VALUE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
class ClusterUtilsTest {
private ClusterUtils clusterUtils;
@BeforeEach
public void setup() {
clusterUtils = new ClusterUtils();
clusterUtils.setApplicationModel(ApplicationModel.defaultModel());
}
@Test
void testMergeUrl() {
URL providerURL = URL.valueOf("dubbo://localhost:55555");
providerURL = providerURL.setPath("path").setUsername("username").setPassword("password");
providerURL = URLBuilder.from(providerURL)
.addParameter(GROUP_KEY, "dubbo")
.addParameter(VERSION_KEY, "1.2.3")
.addParameter(DUBBO_VERSION_KEY, "2.3.7")
.addParameter(THREADPOOL_KEY, "fixed")
.addParameter(THREADS_KEY, Integer.MAX_VALUE)
.addParameter(THREAD_NAME_KEY, "test")
.addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE)
.addParameter(QUEUES_KEY, Integer.MAX_VALUE)
.addParameter(ALIVE_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed")
.addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test")
.addParameter(APPLICATION_KEY, "provider")
.addParameter(REFERENCE_FILTER_KEY, "filter1,filter2")
.addParameter(TAG_KEY, "TTT")
.build();
// Verify default ProviderURLMergeProcessor
URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "consumer")
.addParameter(REFERENCE_FILTER_KEY, "filter3")
.addParameter(TAG_KEY, "UUU")
.build();
URL url = clusterUtils.mergeUrl(providerURL, consumerURL.getParameters());
Assertions.assertFalse(url.hasParameter(THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY));
Assertions.assertFalse(url.hasParameter(CORE_THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY));
Assertions.assertFalse(url.hasParameter(QUEUES_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY));
Assertions.assertFalse(url.hasParameter(ALIVE_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY));
Assertions.assertFalse(url.hasParameter(THREAD_NAME_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY));
Assertions.assertEquals("path", url.getPath());
Assertions.assertEquals("username", url.getUsername());
Assertions.assertEquals("password", url.getPassword());
Assertions.assertEquals("1234", url.getParameter(PID_KEY));
Assertions.assertEquals("foo", url.getParameter(THREADPOOL_KEY));
Assertions.assertEquals("consumer", url.getApplication());
Assertions.assertEquals("provider", url.getRemoteApplication());
Assertions.assertEquals("filter1,filter2,filter3", url.getParameter(REFERENCE_FILTER_KEY));
Assertions.assertEquals("TTT", url.getParameter(TAG_KEY));
// Verify custom ProviderURLMergeProcessor
URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "consumer")
.addParameter(REFERENCE_FILTER_KEY, "filter3")
.addParameter(TAG_KEY, "UUU")
.addParameter(URL_MERGE_PROCESSOR_KEY, "tag")
.build();
URL urlForTag = clusterUtils.mergeUrl(providerURL, consumerUrlForTag.getParameters());
Assertions.assertEquals("UUU", urlForTag.getParameter(TAG_KEY));
}
@Test
void testMergeLocalParams() {
// Verify default ProviderURLMergeProcessor
URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "consumer")
.addParameter(REFERENCE_FILTER_KEY, "filter3")
.addParameter(TAG_KEY, "UUU")
.build();
Map<String, String> params = clusterUtils.mergeLocalParams(consumerURL.getParameters());
Assertions.assertEquals("1234", params.get(PID_KEY));
Assertions.assertEquals("foo", params.get(THREADPOOL_KEY));
Assertions.assertEquals("consumer", params.get(APPLICATION_KEY));
Assertions.assertEquals("filter3", params.get(REFERENCE_FILTER_KEY));
Assertions.assertEquals("UUU", params.get(TAG_KEY));
// Verify custom ProviderURLMergeProcessor
URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "consumer")
.addParameter(REFERENCE_FILTER_KEY, "filter3")
.addParameter(TAG_KEY, "UUU")
.addParameter(URL_MERGE_PROCESSOR_KEY, "tag")
.build();
Map<String, String> paramsForTag = clusterUtils.mergeLocalParams(consumerUrlForTag.getParameters());
Assertions.assertEquals("1234", paramsForTag.get(PID_KEY));
Assertions.assertEquals("foo", paramsForTag.get(THREADPOOL_KEY));
Assertions.assertEquals("consumer", paramsForTag.get(APPLICATION_KEY));
Assertions.assertEquals("filter3", paramsForTag.get(REFERENCE_FILTER_KEY));
Assertions.assertNull(paramsForTag.get(TAG_KEY));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.LogUtil;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
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.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* FailbackClusterInvokerTest
* <p>
* add annotation @TestMethodOrder, the testARetryFailed Method must to first execution
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class FailbackClusterInvokerTest {
List<Invoker<FailbackClusterInvokerTest>> invokers = new ArrayList<>();
URL url = URL.valueOf("test://test:11/test?retries=2&failbacktasks=2");
Invoker<FailbackClusterInvokerTest> invoker = mock(Invoker.class);
RpcInvocation invocation = new RpcInvocation();
Directory<FailbackClusterInvokerTest> dic;
Result result = new AppResponse();
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
RpcContext.removeServiceContext();
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker);
}
@AfterEach
public void tearDown() {
dic = null;
invocation = new RpcInvocation();
invokers.clear();
}
private void resetInvokerToException() {
given(invoker.invoke(invocation)).willThrow(new RuntimeException());
given(invoker.getUrl()).willReturn(url);
given(invoker.getInterface()).willReturn(FailbackClusterInvokerTest.class);
}
private void resetInvokerToNoException() {
given(invoker.invoke(invocation)).willReturn(result);
given(invoker.getUrl()).willReturn(url);
given(invoker.getInterface()).willReturn(FailbackClusterInvokerTest.class);
}
@Test
void testInvokeWithIllegalRetriesParam() {
URL url = URL.valueOf("test://test:11/test?retries=-1&failbacktasks=2");
Directory<FailbackClusterInvokerTest> dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class);
given(dic.list(invocation)).willReturn(invokers);
given(invoker.getUrl()).willReturn(url);
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
invoker.invoke(invocation);
Assertions.assertNull(RpcContext.getServiceContext().getInvoker());
DubboAppender.clear();
}
@Test
void testInvokeWithIllegalFailbacktasksParam() {
URL url = URL.valueOf("test://test:11/test?retries=2&failbacktasks=-1");
Directory<FailbackClusterInvokerTest> dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class);
given(dic.list(invocation)).willReturn(invokers);
given(invoker.getUrl()).willReturn(url);
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
invoker.invoke(invocation);
Assertions.assertNull(RpcContext.getServiceContext().getInvoker());
DubboAppender.clear();
}
@Test
@Order(1)
public void testInvokeException() {
resetInvokerToException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
invoker.invoke(invocation);
Assertions.assertNull(RpcContext.getServiceContext().getInvoker());
DubboAppender.clear();
}
@Test
@Order(2)
public void testInvokeNoException() {
resetInvokerToNoException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
Result ret = invoker.invoke(invocation);
Assertions.assertSame(result, ret);
}
@Test
@Order(3)
public void testNoInvoke() {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(null);
given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker);
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
} catch (RpcException e) {
Assertions.assertTrue(e.getMessage().contains("No provider available"));
assertFalse(e.getCause() instanceof RpcException);
}
}
@Disabled
@Test
@Order(4)
public void testARetryFailed() throws Exception {
// Test retries and
resetInvokerToException();
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
LogUtil.start();
DubboAppender.clear();
invoker.invoke(invocation);
invoker.invoke(invocation);
invoker.invoke(invocation);
Assertions.assertNull(RpcContext.getServiceContext().getInvoker());
// invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked
// invoker,so
// Ensure that the main thread is online
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(15000L, TimeUnit.MILLISECONDS);
LogUtil.stop();
Assertions.assertEquals(
4, LogUtil.findMessage(Level.ERROR, "Failed retry to invoke method"), "must have four error message ");
Assertions.assertEquals(
2,
LogUtil.findMessage(Level.ERROR, "Failed retry times exceed threshold"),
"must have two error message ");
Assertions.assertEquals(
1, LogUtil.findMessage(Level.ERROR, "Failback background works error"), "must have one error message ");
// it can be invoke successfully
}
private long getRetryFailedPeriod() throws NoSuchFieldException, IllegalAccessException {
Field retryFailedPeriod = FailbackClusterInvoker.class.getDeclaredField("RETRY_FAILED_PERIOD");
retryFailedPeriod.setAccessible(true);
return retryFailedPeriod.getLong(FailbackClusterInvoker.class);
}
@Test
@Order(5)
public void testInvokeRetryTimesWithZeroValue()
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
int retries = 0;
resetInvokerToException();
given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries));
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
LogUtil.start();
DubboAppender.clear();
invocation.setMethodName("testInvokeRetryTimesWithZeroValue");
invoker.invoke(invocation);
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS);
LogUtil.stop();
Assertions.assertEquals(
0,
LogUtil.findMessage(
Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithZeroValue"),
"No retry messages allowed");
}
@Test
@Order(6)
public void testInvokeRetryTimesWithTwoValue()
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
int retries = 2;
resetInvokerToException();
given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries));
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
LogUtil.start();
DubboAppender.clear();
invocation.setMethodName("testInvokeRetryTimesWithTwoValue");
invoker.invoke(invocation);
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS);
LogUtil.stop();
Assertions.assertEquals(
2,
LogUtil.findMessage(
Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithTwoValue"),
"Must have two error message ");
}
@Test
@Order(7)
public void testInvokeRetryTimesWithDefaultValue()
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
resetInvokerToException();
given(dic.getConsumerUrl()).willReturn(URL.valueOf("test://test:11/test"));
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
LogUtil.start();
DubboAppender.clear();
invocation.setMethodName("testInvokeRetryTimesWithDefaultValue");
invoker.invoke(invocation);
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS);
LogUtil.stop();
Assertions.assertEquals(
3,
LogUtil.findMessage(
Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithDefaultValue"),
"Must have three error message ");
}
@Test
@Order(8)
public void testInvokeRetryTimesWithIllegalValue()
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
resetInvokerToException();
given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, -100));
FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic);
LogUtil.start();
DubboAppender.clear();
invocation.setMethodName("testInvokeRetryTimesWithIllegalValue");
invoker.invoke(invocation);
CountDownLatch countDown = new CountDownLatch(1);
countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS);
LogUtil.stop();
Assertions.assertEquals(
3,
LogUtil.findMessage(
Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithIllegalValue"),
"Must have three error message ");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/GreetingMock2.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/GreetingMock2.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.rpc.cluster.support;
public class GreetingMock2 implements Greeting {
private GreetingMock2() {}
@Override
public String hello() {
return "mock";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @see BroadcastClusterInvoker
*/
class BroadCastClusterInvokerTest {
private URL url;
private Directory<DemoService> dic;
private RpcInvocation invocation;
private BroadcastClusterInvoker clusterInvoker;
private MockInvoker invoker1;
private MockInvoker invoker2;
private MockInvoker invoker3;
private MockInvoker invoker4;
@BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
invoker1 = new MockInvoker();
invoker2 = new MockInvoker();
invoker3 = new MockInvoker();
invoker4 = new MockInvoker();
url = URL.valueOf("test://127.0.0.1:8080/test");
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.getInterface()).willReturn(DemoService.class);
invocation = new RpcInvocation();
invocation.setMethodName("test");
clusterInvoker = new BroadcastClusterInvoker(dic);
}
@Test
void testNormal() {
given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4));
// Every invoker will be called
clusterInvoker.invoke(invocation);
assertTrue(invoker1.isInvoked());
assertTrue(invoker2.isInvoked());
assertTrue(invoker3.isInvoked());
assertTrue(invoker4.isInvoked());
}
@Test
void testEx() {
given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4));
invoker1.invokeThrowEx();
assertThrows(RpcException.class, () -> {
clusterInvoker.invoke(invocation);
});
// The default failure percentage is 100, even if a certain invoker#invoke throws an exception, other invokers
// will still be called
assertTrue(invoker1.isInvoked());
assertTrue(invoker2.isInvoked());
assertTrue(invoker3.isInvoked());
assertTrue(invoker4.isInvoked());
}
@Test
void testFailPercent() {
given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4));
// We set the failure percentage to 75, which means that when the number of call failures is 4*(75/100) = 3,
// an exception will be thrown directly and subsequent invokers will not be called.
url = url.addParameter("broadcast.fail.percent", 75);
given(dic.getConsumerUrl()).willReturn(url);
invoker1.invokeThrowEx();
invoker2.invokeThrowEx();
invoker3.invokeThrowEx();
invoker4.invokeThrowEx();
assertThrows(RpcException.class, () -> {
clusterInvoker.invoke(invocation);
});
assertTrue(invoker1.isInvoked());
assertTrue(invoker2.isInvoked());
assertTrue(invoker3.isInvoked());
assertFalse(invoker4.isInvoked());
}
}
class MockInvoker implements Invoker<DemoService> {
private static int count = 0;
private URL url = URL.valueOf("test://127.0.0.1:8080/test");
private boolean throwEx = false;
private boolean invoked = false;
@Override
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void destroy() {}
@Override
public Class<DemoService> getInterface() {
return DemoService.class;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
invoked = true;
if (throwEx) {
throwEx = false;
throw new RpcException();
}
return null;
}
public void invokeThrowEx() {
throwEx = true;
}
public boolean isInvoked() {
return invoked;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Test for AvailableClusterInvoker
*/
class AvailableClusterInvokerTest {
private final URL url = URL.valueOf("test://test:80/test");
private final Invoker<AvailableClusterInvokerTest> invoker1 = mock(Invoker.class);
private final Invoker<AvailableClusterInvokerTest> invoker2 = mock(Invoker.class);
private final Invoker<AvailableClusterInvokerTest> invoker3 = mock(Invoker.class);
private final RpcInvocation invocation = new RpcInvocation();
private final Result result = new AppResponse();
private final List<Invoker<AvailableClusterInvokerTest>> invokers = new ArrayList<>();
private Directory<AvailableClusterInvokerTest> dic;
@BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(AvailableClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
}
private void resetInvokerToNoException() {
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getInterface()).willReturn(AvailableClusterInvokerTest.class);
given(invoker2.invoke(invocation)).willReturn(result);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(AvailableClusterInvokerTest.class);
given(invoker3.invoke(invocation)).willReturn(result);
given(invoker3.getUrl()).willReturn(url);
given(invoker3.isAvailable()).willReturn(true);
given(invoker3.getInterface()).willReturn(AvailableClusterInvokerTest.class);
}
@Test
void testInvokeNoException() {
resetInvokerToNoException();
AvailableClusterInvoker<AvailableClusterInvokerTest> invoker = new AvailableClusterInvoker<>(dic);
Result ret = invoker.invoke(invocation);
Assertions.assertSame(result, ret);
}
@Test
void testInvokeWithException() {
// remove invokers for test exception
dic.list(invocation).removeAll(invokers);
AvailableClusterInvoker<AvailableClusterInvokerTest> invoker = new AvailableClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
fail();
} catch (RpcException e) {
Assertions.assertTrue(e.getMessage().contains("No provider available"));
assertFalse(e.getCause() instanceof RpcException);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
public class TagProviderURLMergeProcessor implements ProviderURLMergeProcessor {
@Override
public URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap) {
String tag = localParametersMap.get(TAG_KEY);
remoteUrl = remoteUrl.removeParameter(TAG_KEY);
remoteUrl = remoteUrl.addParameter(TAG_KEY, tag);
return remoteUrl;
}
@Override
public Map<String, String> mergeLocalParams(Map<String, String> localMap) {
localMap.remove(TAG_KEY);
return ProviderURLMergeProcessor.super.mergeLocalParams(localMap);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/GreetingMock1.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/GreetingMock1.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.rpc.cluster.support;
public class GreetingMock1 {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.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.rpc.cluster.support;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Menu {
private Map<String, List<String>> menus = new HashMap<String, List<String>>();
public Menu() {}
public Menu(Map<String, List<String>> menus) {
for (Map.Entry<String, List<String>> entry : menus.entrySet()) {
this.menus.put(entry.getKey(), new ArrayList<String>(entry.getValue()));
}
}
public void putMenuItem(String menu, String item) {
List<String> items = menus.get(menu);
if (item == null) {
items = new ArrayList<String>();
menus.put(menu, items);
}
items.add(item);
}
public void addMenu(String menu, List<String> items) {
List<String> menuItems = menus.get(menu);
if (menuItems == null) {
menus.put(menu, new ArrayList<String>(items));
} else {
menuItems.addAll(new ArrayList<String>(items));
}
}
public Map<String, List<String>> getMenus() {
return Collections.unmodifiableMap(menus);
}
public void merge(Menu menu) {
for (Map.Entry<String, List<String>> entry : menu.menus.entrySet()) {
addMenu(entry.getKey(), entry.getValue());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class FailfastClusterInvokerTest {
List<Invoker<FailfastClusterInvokerTest>> invokers = new ArrayList<>();
URL url = URL.valueOf("test://test:11/test");
Invoker<FailfastClusterInvokerTest> invoker1 = mock(Invoker.class);
RpcInvocation invocation = new RpcInvocation();
Directory<FailfastClusterInvokerTest> dic;
Result result = new AppResponse();
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(invokers);
given(dic.getInterface()).willReturn(FailfastClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
}
private void resetInvoker1ToException() {
given(invoker1.invoke(invocation)).willThrow(new RuntimeException());
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class);
}
private void resetInvoker1ToNoException() {
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class);
}
@Test
void testInvokeException() {
Assertions.assertThrows(RpcException.class, () -> {
resetInvoker1ToException();
FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic);
invoker.invoke(invocation);
assertSame(invoker1, RpcContext.getServiceContext().getInvoker());
});
}
@Test
void testInvokeBizException() {
given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION));
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class);
FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic);
try {
Result ret = invoker.invoke(invocation);
assertSame(result, ret);
fail();
} catch (RpcException expected) {
assertEquals(expected.getCode(), RpcException.BIZ_EXCEPTION);
}
}
@Test
void testInvokeNoException() {
resetInvoker1ToNoException();
FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic);
Result ret = invoker.invoke(invocation);
assertSame(result, ret);
}
@Test
void testNoInvoke() {
dic = mock(Directory.class);
given(dic.getUrl()).willReturn(url);
given(dic.getConsumerUrl()).willReturn(url);
given(dic.list(invocation)).willReturn(null);
given(dic.getInterface()).willReturn(FailfastClusterInvokerTest.class);
invocation.setMethodName("method1");
invokers.add(invoker1);
resetInvoker1ToNoException();
FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic);
try {
invoker.invoke(invocation);
fail();
} catch (RpcException expected) {
assertFalse(expected.getCause() instanceof RpcException);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;
import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@SuppressWarnings("rawtypes")
class AbstractClusterInvokerTest {
List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>();
List<Invoker<IHelloService>> selectedInvokers = new ArrayList<Invoker<IHelloService>>();
AbstractClusterInvoker<IHelloService> cluster;
AbstractClusterInvoker<IHelloService> cluster_nocheck;
StaticDirectory<IHelloService> dic;
RpcInvocation invocation = new RpcInvocation();
URL url = URL.valueOf(
"registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer="
+ URL.encode("application=abstractClusterInvokerTest"));
URL consumerUrl = URL.valueOf(
"dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest");
Invoker<IHelloService> invoker1;
Invoker<IHelloService> invoker2;
Invoker<IHelloService> invoker3;
Invoker<IHelloService> invoker4;
Invoker<IHelloService> invoker5;
Invoker<IHelloService> mockedInvoker1;
@BeforeAll
public static void setUpBeforeClass() throws Exception {
System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false");
}
@AfterEach
public void teardown() throws Exception {
RpcContext.removeContext();
}
@AfterAll
public static void afterClass() {
System.clearProperty(ENABLE_CONNECTIVITY_VALIDATION);
}
@SuppressWarnings({"unchecked"})
@BeforeEach
public void setUp() throws Exception {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
Map<String, Object> attributes = new HashMap<>();
attributes.put("application", "abstractClusterInvokerTest");
url = url.putAttribute(REFER_KEY, attributes);
invocation.setMethodName("sayHello");
invoker1 = mock(Invoker.class);
invoker2 = mock(Invoker.class);
invoker3 = mock(Invoker.class);
invoker4 = mock(Invoker.class);
invoker5 = mock(Invoker.class);
mockedInvoker1 = mock(Invoker.class);
URL turl = URL.valueOf("test://test:11/test");
given(invoker1.isAvailable()).willReturn(false);
given(invoker1.getInterface()).willReturn(IHelloService.class);
given(invoker1.getUrl()).willReturn(turl.setPort(1).addParameter("name", "invoker1"));
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(IHelloService.class);
given(invoker2.getUrl()).willReturn(turl.setPort(2).addParameter("name", "invoker2"));
given(invoker3.isAvailable()).willReturn(false);
given(invoker3.getInterface()).willReturn(IHelloService.class);
given(invoker3.getUrl()).willReturn(turl.setPort(3).addParameter("name", "invoker3"));
given(invoker4.isAvailable()).willReturn(true);
given(invoker4.getInterface()).willReturn(IHelloService.class);
given(invoker4.getUrl()).willReturn(turl.setPort(4).addParameter("name", "invoker4"));
given(invoker5.isAvailable()).willReturn(false);
given(invoker5.getInterface()).willReturn(IHelloService.class);
given(invoker5.getUrl()).willReturn(turl.setPort(5).addParameter("name", "invoker5"));
given(mockedInvoker1.isAvailable()).willReturn(false);
given(mockedInvoker1.getInterface()).willReturn(IHelloService.class);
given(mockedInvoker1.getUrl()).willReturn(turl.setPort(999).setProtocol("mock"));
invokers.add(invoker1);
dic = new StaticDirectory<IHelloService>(url, invokers, null);
cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
};
cluster_nocheck =
new AbstractClusterInvoker(
dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
};
}
@Disabled(
"RpcContext attachments will be set to Invocation twice, first in ConsumerContextFilter, second AbstractInvoker")
@Test
void testBindingAttachment() {
final String attachKey = "attach";
final String attachValue = "value";
// setup attachment
RpcContext.getClientAttachment().setAttachment(attachKey, attachValue);
Map<String, Object> attachments = RpcContext.getClientAttachment().getObjectAttachments();
Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!");
cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
// attachment will be bind to invocation
String value = invocation.getAttachment(attachKey);
Assertions.assertNotNull(value);
Assertions.assertEquals(attachValue, value, "binding attachment failed!");
return null;
}
};
// invoke
cluster.invoke(invocation);
}
@Test
void testSelect_Invokersize0() {
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!");
{
Invoker invoker = cluster.select(l, null, null, null);
Assertions.assertNull(invoker);
}
{
invokers.clear();
selectedInvokers.clear();
Invoker invoker = cluster.select(l, null, invokers, null);
Assertions.assertNull(invoker);
}
}
@Test
void testSelectedInvokers() {
cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
checkInvokers(invokers, invocation);
Invoker invoker = select(loadbalance, invocation, invokers, null);
return invokeWithContext(invoker, invocation);
}
};
// invoke
cluster.invoke(invocation);
Assertions.assertEquals(Collections.singletonList(invoker1), invocation.getInvokedInvokers());
}
@Test
void testSelect_Invokersize1() {
invokers.clear();
invokers.add(invoker1);
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!");
Invoker invoker = cluster.select(l, null, invokers, null);
Assertions.assertEquals(invoker1, invoker);
}
@Test
void testSelect_Invokersize2AndselectNotNull() {
invokers.clear();
invokers.add(invoker2);
invokers.add(invoker4);
LoadBalance l = cluster.initLoadBalance(invokers, invocation);
Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!");
{
selectedInvokers.clear();
selectedInvokers.add(invoker4);
Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers);
Assertions.assertEquals(invoker2, invoker);
}
{
selectedInvokers.clear();
selectedInvokers.add(invoker2);
Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers);
Assertions.assertEquals(invoker4, invoker);
}
}
@Test
void testSelect_multiInvokers() {
testSelect_multiInvokers(RoundRobinLoadBalance.NAME);
testSelect_multiInvokers(LeastActiveLoadBalance.NAME);
testSelect_multiInvokers(RandomLoadBalance.NAME);
}
@Test
void testCloseAvailablecheck() {
LoadBalance lb = mock(LoadBalance.class);
Map<String, String> queryMap = (Map<String, String>) url.getAttribute(REFER_KEY);
URL tmpUrl = turnRegistryUrlToConsumerUrl(url, queryMap);
when(lb.select(same(invokers), eq(tmpUrl), same(invocation))).thenReturn(invoker1);
initlistsize5();
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertFalse(sinvoker.isAvailable());
Assertions.assertEquals(invoker1, sinvoker);
}
private URL turnRegistryUrlToConsumerUrl(URL url, Map<String, String> queryMap) {
String host =
StringUtils.isNotEmpty(queryMap.get("register.ip")) ? queryMap.get("register.ip") : this.url.getHost();
String path = queryMap.get(PATH_KEY);
String consumedProtocol = queryMap.get(PROTOCOL_KEY) == null ? CONSUMER : queryMap.get(PROTOCOL_KEY);
URL consumerUrlFrom = this.url
.setHost(host)
.setPort(0)
.setProtocol(consumedProtocol)
.setPath(path == null ? queryMap.get(INTERFACE_KEY) : path);
return consumerUrlFrom.addParameters(queryMap).removeParameter(MONITOR_KEY);
}
@Test
void testDonotSelectAgainAndNoCheckAvailable() {
LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME);
initlistsize5();
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertSame(invoker1, sinvoker);
}
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertSame(invoker2, sinvoker);
}
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertSame(invoker3, sinvoker);
}
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertSame(invoker5, sinvoker);
}
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(invokers.contains(sinvoker));
}
}
@Test
void testSelectAgainAndCheckAvailable() {
LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME);
initlistsize5();
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertSame(sinvoker, invoker4);
}
{
// Boundary condition test .
selectedInvokers.clear();
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
{
// Boundary condition test .
for (int i = 0; i < 100; i++) {
selectedInvokers.clear();
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
{
// Boundary condition test .
for (int i = 0; i < 100; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
{
// Boundary condition test .
for (int i = 0; i < 100; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker4);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4);
}
}
}
public void testSelect_multiInvokers(String lbname) {
int min = 100, max = 500;
Double d = (Math.random() * (max - min + 1) + min);
int runs = d.intValue();
Assertions.assertTrue(runs >= min);
LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(lbname);
initlistsize5();
for (int i = 0; i < runs; i++) {
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker2);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker4);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker3);
selectedInvokers.add(invoker5);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
selectedInvokers.add(invoker1);
selectedInvokers.add(invoker2);
selectedInvokers.add(invoker3);
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
Assertions.assertTrue(sinvoker.isAvailable());
Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5);
}
}
/**
* Test balance.
*/
@Test
void testSelectBalance() {
LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME);
initlistsize5();
Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>();
for (Invoker invoker : invokers) {
counter.put(invoker, new AtomicLong(0));
}
int runs = 1000;
for (int i = 0; i < runs; i++) {
selectedInvokers.clear();
Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers);
counter.get(sinvoker).incrementAndGet();
}
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
if (entry.getKey().isAvailable())
Assertions.assertTrue(count > runs / invokers.size(), "count should > avg");
}
Assertions.assertEquals(
runs, counter.get(invoker2).get() + counter.get(invoker4).get());
}
private void initlistsize5() {
invokers.clear();
selectedInvokers
.clear(); // Clear first, previous test case will make sure that the right invoker2 will be used.
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
invokers.add(invoker4);
invokers.add(invoker5);
}
private void initDic() {
dic.notify(invokers);
dic.buildRouterChain();
}
@Test
void testTimeoutExceptionCode() {
List<Invoker<DemoService>> invokers = new ArrayList<Invoker<DemoService>>();
invokers.add(new Invoker<DemoService>() {
@Override
public Class<DemoService> getInterface() {
return DemoService.class;
}
public URL getUrl() {
return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/" + DemoService.class.getName());
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test timeout");
}
@Override
public void destroy() {}
});
Directory<DemoService> directory = new StaticDirectory<DemoService>(invokers);
FailoverClusterInvoker<DemoService> failoverClusterInvoker = new FailoverClusterInvoker<DemoService>(directory);
RpcInvocation invocation =
new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
try {
failoverClusterInvoker.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
ForkingClusterInvoker<DemoService> forkingClusterInvoker = new ForkingClusterInvoker<DemoService>(directory);
invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
try {
forkingClusterInvoker.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
FailfastClusterInvoker<DemoService> failfastClusterInvoker = new FailfastClusterInvoker<DemoService>(directory);
invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
try {
failfastClusterInvoker.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode());
}
}
public static interface IHelloService {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.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.rpc.cluster.support;
import java.util.List;
public interface MenuService {
Menu getMenu();
void addMenu(String menu, List<String> items);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.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.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
@SuppressWarnings("all")
class ConnectivityValidationTest {
private Invoker invoker1;
private Invoker invoker2;
private Invoker invoker3;
private Invoker invoker4;
private Invoker invoker5;
private Invoker invoker6;
private Invoker invoker7;
private Invoker invoker8;
private Invoker invoker9;
private Invoker invoker10;
private Invoker invoker11;
private Invoker invoker12;
private Invoker invoker13;
private Invoker invoker14;
private Invoker invoker15;
private List<Invoker> invokerList;
private StaticDirectory directory;
private ConnectivityClusterInvoker clusterInvoker;
@BeforeEach
public void setup() {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
invoker1 = Mockito.mock(Invoker.class);
invoker2 = Mockito.mock(Invoker.class);
invoker3 = Mockito.mock(Invoker.class);
invoker4 = Mockito.mock(Invoker.class);
invoker5 = Mockito.mock(Invoker.class);
invoker6 = Mockito.mock(Invoker.class);
invoker7 = Mockito.mock(Invoker.class);
invoker8 = Mockito.mock(Invoker.class);
invoker9 = Mockito.mock(Invoker.class);
invoker10 = Mockito.mock(Invoker.class);
invoker11 = Mockito.mock(Invoker.class);
invoker12 = Mockito.mock(Invoker.class);
invoker13 = Mockito.mock(Invoker.class);
invoker14 = Mockito.mock(Invoker.class);
invoker15 = Mockito.mock(Invoker.class);
configInvoker(invoker1);
configInvoker(invoker2);
configInvoker(invoker3);
configInvoker(invoker4);
configInvoker(invoker5);
configInvoker(invoker6);
configInvoker(invoker7);
configInvoker(invoker8);
configInvoker(invoker9);
configInvoker(invoker10);
configInvoker(invoker11);
configInvoker(invoker12);
configInvoker(invoker13);
configInvoker(invoker14);
configInvoker(invoker15);
invokerList = new LinkedList<>();
invokerList.add(invoker1);
invokerList.add(invoker2);
invokerList.add(invoker3);
invokerList.add(invoker4);
invokerList.add(invoker5);
directory = new StaticDirectory(invokerList);
clusterInvoker = new ConnectivityClusterInvoker(directory);
}
@AfterEach
public void tearDown() {
clusterInvoker.destroy();
}
private void configInvoker(Invoker invoker) {
when(invoker.getUrl()).thenReturn(URL.valueOf(""));
when(invoker.isAvailable()).thenReturn(true);
}
@BeforeAll
public static void setupClass() {
System.setProperty(CommonConstants.RECONNECT_TASK_PERIOD, "1");
}
@AfterAll
public static void clearAfterClass() {
System.clearProperty(CommonConstants.RECONNECT_TASK_PERIOD);
}
@Test
void testBasic() throws InterruptedException {
Invocation invocation = new RpcInvocation();
LoadBalance loadBalance = new RandomLoadBalance();
Assertions.assertEquals(5, directory.list(invocation).size());
Assertions.assertNotNull(
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
when(invoker1.isAvailable()).thenReturn(false);
when(invoker2.isAvailable()).thenReturn(false);
when(invoker3.isAvailable()).thenReturn(false);
when(invoker4.isAvailable()).thenReturn(false);
when(invoker5.isAvailable()).thenReturn(false);
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList());
Assertions.assertEquals(0, directory.list(invocation).size());
when(invoker1.isAvailable()).thenReturn(true);
Set<Invoker> invokerSet = new HashSet<>();
invokerSet.add(invoker1);
waitRefresh(invokerSet);
Assertions.assertEquals(1, directory.list(invocation).size());
Assertions.assertNotNull(
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
when(invoker2.isAvailable()).thenReturn(true);
invokerSet.add(invoker2);
waitRefresh(invokerSet);
Assertions.assertEquals(2, directory.list(invocation).size());
Assertions.assertNotNull(
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
invokerList.remove(invoker5);
directory.notify(invokerList);
when(invoker2.isAvailable()).thenReturn(true);
waitRefresh(invokerSet);
Assertions.assertEquals(2, directory.list(invocation).size());
Assertions.assertNotNull(
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
when(invoker3.isAvailable()).thenReturn(true);
when(invoker4.isAvailable()).thenReturn(true);
invokerSet.add(invoker3);
invokerSet.add(invoker4);
waitRefresh(invokerSet);
Assertions.assertEquals(4, directory.list(invocation).size());
Assertions.assertNotNull(
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
}
@Test
void testRetry() throws InterruptedException {
Invocation invocation = new RpcInvocation();
LoadBalance loadBalance = new RandomLoadBalance();
invokerList.clear();
invokerList.add(invoker1);
invokerList.add(invoker2);
directory.notify(invokerList);
Assertions.assertEquals(2, directory.list(invocation).size());
when(invoker1.isAvailable()).thenReturn(false);
Assertions.assertEquals(
invoker2,
clusterInvoker.select(
loadBalance, invocation, directory.list(invocation), Collections.singletonList(invoker2)));
Assertions.assertEquals(1, directory.list(invocation).size());
when(invoker1.isAvailable()).thenReturn(true);
Set<Invoker> invokerSet = new HashSet<>();
invokerSet.add(invoker1);
waitRefresh(invokerSet);
Assertions.assertEquals(2, directory.list(invocation).size());
}
@Test
void testRandomSelect() throws InterruptedException {
Invocation invocation = new RpcInvocation();
LoadBalance loadBalance = new RandomLoadBalance();
invokerList.add(invoker6);
invokerList.add(invoker7);
invokerList.add(invoker8);
invokerList.add(invoker9);
invokerList.add(invoker10);
invokerList.add(invoker11);
invokerList.add(invoker12);
invokerList.add(invoker13);
invokerList.add(invoker14);
invokerList.add(invoker15);
directory.notify(invokerList);
Assertions.assertEquals(15, directory.list(invocation).size());
when(invoker2.isAvailable()).thenReturn(false);
when(invoker3.isAvailable()).thenReturn(false);
when(invoker4.isAvailable()).thenReturn(false);
when(invoker5.isAvailable()).thenReturn(false);
when(invoker6.isAvailable()).thenReturn(false);
when(invoker7.isAvailable()).thenReturn(false);
when(invoker8.isAvailable()).thenReturn(false);
when(invoker9.isAvailable()).thenReturn(false);
when(invoker10.isAvailable()).thenReturn(false);
when(invoker11.isAvailable()).thenReturn(false);
when(invoker12.isAvailable()).thenReturn(false);
when(invoker13.isAvailable()).thenReturn(false);
when(invoker14.isAvailable()).thenReturn(false);
when(invoker15.isAvailable()).thenReturn(false);
for (int i = 0; i < 15; i++) {
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList());
}
for (int i = 0; i < 5; i++) {
Assertions.assertEquals(
invoker1,
clusterInvoker.select(
loadBalance, invocation, directory.list(invocation), Collections.emptyList()));
}
when(invoker1.isAvailable()).thenReturn(false);
clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList());
Assertions.assertEquals(0, directory.list(invocation).size());
when(invoker1.isAvailable()).thenReturn(true);
when(invoker2.isAvailable()).thenReturn(true);
when(invoker3.isAvailable()).thenReturn(true);
when(invoker4.isAvailable()).thenReturn(true);
when(invoker5.isAvailable()).thenReturn(true);
when(invoker6.isAvailable()).thenReturn(true);
when(invoker7.isAvailable()).thenReturn(true);
when(invoker8.isAvailable()).thenReturn(true);
when(invoker9.isAvailable()).thenReturn(true);
when(invoker10.isAvailable()).thenReturn(true);
when(invoker11.isAvailable()).thenReturn(true);
when(invoker12.isAvailable()).thenReturn(true);
when(invoker13.isAvailable()).thenReturn(true);
when(invoker14.isAvailable()).thenReturn(true);
when(invoker15.isAvailable()).thenReturn(true);
Set<Invoker> invokerSet = new HashSet<>();
invokerSet.add(invoker1);
invokerSet.add(invoker2);
invokerSet.add(invoker3);
invokerSet.add(invoker4);
invokerSet.add(invoker5);
invokerSet.add(invoker6);
invokerSet.add(invoker7);
invokerSet.add(invoker8);
invokerSet.add(invoker9);
invokerSet.add(invoker10);
invokerSet.add(invoker11);
invokerSet.add(invoker12);
invokerSet.add(invoker13);
invokerSet.add(invoker14);
invokerSet.add(invoker15);
waitRefresh(invokerSet);
Assertions.assertTrue(directory.list(invocation).size() > 1);
}
private static class ConnectivityClusterInvoker<T> extends AbstractClusterInvoker<T> {
public ConnectivityClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
public Invoker<T> select(
LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected)
throws RpcException {
return super.select(loadbalance, invocation, invokers, selected);
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
}
private void waitRefresh(Set<Invoker> invokerSet) throws InterruptedException {
directory.checkConnectivity();
while (true) {
List<Invoker> reconnectList = directory.getInvokersToReconnect();
if (reconnectList.stream().anyMatch(invoker -> invokerSet.contains(invoker))) {
Thread.sleep(10);
continue;
}
break;
}
}
private static class RandomLoadBalance implements LoadBalance {
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
return CollectionUtils.isNotEmpty(invokers)
? invokers.get(ThreadLocalRandom.current().nextInt(invokers.size()))
: null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceAMock.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/DemoServiceAMock.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.rpc.cluster.support;
/**
* default mock service for DemoServiceA
*/
public class DemoServiceAMock implements DemoServiceA {
public static final String MOCK_VALUE = "mockA";
@Override
public String methodA() {
return MOCK_VALUE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Greeting.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Greeting.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.rpc.cluster.support;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface Greeting {
String hello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.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.rpc.cluster.support.merger;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
class DefaultProviderURLMergeProcessorTest {
private ProviderURLMergeProcessor providerURLMergeProcessor;
@BeforeEach
public void setup() {
providerURLMergeProcessor = new DefaultProviderURLMergeProcessor();
}
@Test
void testMergeUrl() {
URL providerURL = URL.valueOf("dubbo://localhost:55555");
providerURL = providerURL.setPath("path").setUsername("username").setPassword("password");
providerURL = URLBuilder.from(providerURL)
.addParameter(GROUP_KEY, "dubbo")
.addParameter(VERSION_KEY, "1.2.3")
.addParameter(DUBBO_VERSION_KEY, "2.3.7")
.addParameter(THREADPOOL_KEY, "fixed")
.addParameter(THREADS_KEY, Integer.MAX_VALUE)
.addParameter(THREAD_NAME_KEY, "test")
.addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE)
.addParameter(QUEUES_KEY, Integer.MAX_VALUE)
.addParameter(ALIVE_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed")
.addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE)
.addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test")
.addParameter(APPLICATION_KEY, "provider")
.addParameter(REFERENCE_FILTER_KEY, "filter1,filter2")
.addParameter(TAG_KEY, "TTT")
.build();
URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555)
.addParameter(PID_KEY, "1234")
.addParameter(THREADPOOL_KEY, "foo")
.addParameter(APPLICATION_KEY, "consumer")
.addParameter(REFERENCE_FILTER_KEY, "filter3")
.addParameter(TAG_KEY, "UUU")
.build();
URL url = providerURLMergeProcessor.mergeUrl(providerURL, consumerURL.getParameters());
Assertions.assertFalse(url.hasParameter(THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY));
Assertions.assertFalse(url.hasParameter(CORE_THREADS_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY));
Assertions.assertFalse(url.hasParameter(QUEUES_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY));
Assertions.assertFalse(url.hasParameter(ALIVE_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY));
Assertions.assertFalse(url.hasParameter(THREAD_NAME_KEY));
Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY));
Assertions.assertEquals("path", url.getPath());
Assertions.assertEquals("username", url.getUsername());
Assertions.assertEquals("password", url.getPassword());
Assertions.assertEquals("1234", url.getParameter(PID_KEY));
Assertions.assertEquals("foo", url.getParameter(THREADPOOL_KEY));
Assertions.assertEquals("consumer", url.getApplication());
Assertions.assertEquals("provider", url.getRemoteApplication());
Assertions.assertEquals("filter1,filter2,filter3", url.getParameter(REFERENCE_FILTER_KEY));
Assertions.assertEquals("TTT", url.getParameter(TAG_KEY));
}
@Test
void testUseProviderParams() {
// present in both local and remote, but uses remote value.
URL localURL =
URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local"
+ "&methods=local&tag=local×tamp=local");
URL remoteURL = URL.valueOf(
"dubbo://localhost:20880/DemoService?version=remote&group=remote&dubbo=remote&release=remote"
+ "&methods=remote&tag=remote×tamp=remote");
URL mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters());
Assertions.assertEquals(remoteURL.getVersion(), mergedUrl.getVersion());
Assertions.assertEquals(remoteURL.getGroup(), mergedUrl.getGroup());
Assertions.assertEquals(remoteURL.getParameter(DUBBO_VERSION_KEY), mergedUrl.getParameter(DUBBO_VERSION_KEY));
Assertions.assertEquals(remoteURL.getParameter(RELEASE_KEY), mergedUrl.getParameter(RELEASE_KEY));
Assertions.assertEquals(remoteURL.getParameter(METHODS_KEY), mergedUrl.getParameter(METHODS_KEY));
Assertions.assertEquals(remoteURL.getParameter(TIMESTAMP_KEY), mergedUrl.getParameter(TIMESTAMP_KEY));
Assertions.assertEquals(remoteURL.getParameter(TAG_KEY), mergedUrl.getParameter(TAG_KEY));
// present in local url but not in remote url, parameters of remote url is empty
localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local"
+ "&methods=local&tag=local×tamp=local");
remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService");
mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters());
Assertions.assertEquals(localURL.getVersion(), mergedUrl.getVersion());
Assertions.assertEquals(localURL.getGroup(), mergedUrl.getGroup());
Assertions.assertNull(mergedUrl.getParameter(DUBBO_VERSION_KEY));
Assertions.assertNull(mergedUrl.getParameter(RELEASE_KEY));
Assertions.assertNull(mergedUrl.getParameter(METHODS_KEY));
Assertions.assertNull(mergedUrl.getParameter(TIMESTAMP_KEY));
Assertions.assertNull(mergedUrl.getParameter(TAG_KEY));
// present in local url but not in remote url
localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local"
+ "&methods=local&tag=local×tamp=local");
remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?key=value");
mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters());
Assertions.assertEquals(localURL.getVersion(), mergedUrl.getVersion());
Assertions.assertEquals(localURL.getGroup(), mergedUrl.getGroup());
Assertions.assertNull(mergedUrl.getParameter(DUBBO_VERSION_KEY));
Assertions.assertNull(mergedUrl.getParameter(RELEASE_KEY));
Assertions.assertNull(mergedUrl.getParameter(METHODS_KEY));
Assertions.assertNull(mergedUrl.getParameter(TIMESTAMP_KEY));
Assertions.assertNull(mergedUrl.getParameter(TAG_KEY));
// present in both local and remote, uses local url params
localURL = URL.valueOf("dubbo://localhost:20880/DemoService?loadbalance=local&timeout=1000&cluster=local");
remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?loadbalance=remote&timeout=2000&cluster=remote");
mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters());
Assertions.assertEquals(localURL.getParameter(CLUSTER_KEY), mergedUrl.getParameter(CLUSTER_KEY));
Assertions.assertEquals(localURL.getParameter(TIMEOUT_KEY), mergedUrl.getParameter(TIMEOUT_KEY));
Assertions.assertEquals(localURL.getParameter(LOADBALANCE_KEY), mergedUrl.getParameter(LOADBALANCE_KEY));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.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.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
class MockProviderRpcExceptionTest {
private static final Logger logger = LoggerFactory.getLogger(MockProviderRpcExceptionTest.class);
List<Invoker<IHelloRpcService>> invokers = new ArrayList<Invoker<IHelloRpcService>>();
@BeforeEach
public void beforeMethod() {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
invokers.clear();
}
/**
* Test if mock policy works fine: ProviderRpcException
*/
@Test
void testMockInvokerProviderRpcException() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloRpcService.class.getName());
url = url.addParameter(MOCK_KEY, "true")
.addParameter("invoke_return_error", "true")
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloRpcService.class.getName()
+ "&" + "mock=true"
+ "&" + "proxy=jdk"));
Invoker<IHelloRpcService> cluster = getClusterInvoker(url);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething4");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("something4mock", ret.getValue());
}
private Invoker<IHelloRpcService> getClusterInvokerMock(URL url, Invoker<IHelloRpcService> mockInvoker) {
// As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains
// complete parameter type information
final URL durl = url.addParameter("proxy", "jdk");
invokers.clear();
ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk");
Invoker<IHelloRpcService> invoker1 = proxy.getInvoker(new HelloRpcService(), IHelloRpcService.class, durl);
invokers.add(invoker1);
if (mockInvoker != null) {
invokers.add(mockInvoker);
}
StaticDirectory<IHelloRpcService> dic = new StaticDirectory<IHelloRpcService>(durl, invokers, null);
dic.buildRouterChain();
AbstractClusterInvoker<IHelloRpcService> cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
if (durl.getParameter("invoke_return_error", false)) {
throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception ");
} else {
return ((Invoker<?>) invokers.get(0)).invoke(invocation);
}
}
};
return new MockClusterInvoker<IHelloRpcService>(dic, cluster);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Invoker<IHelloRpcService> getClusterInvoker(URL url) {
return getClusterInvokerMock(url, null);
}
public static interface IHelloRpcService {
String getSomething();
String getSomething2();
String getSomething3();
String getSomething4();
int getInt1();
boolean getBoolean1();
Boolean getBoolean2();
public List<String> getListString();
public List<User> getUsers();
void sayHello();
}
public static class HelloRpcService implements IHelloRpcService {
public String getSomething() {
return "something";
}
public String getSomething2() {
return "something2";
}
public String getSomething3() {
return "something3";
}
public String getSomething4() {
throw new RpcException("getSomething4|RpcException");
}
public int getInt1() {
return 1;
}
public boolean getBoolean1() {
return false;
}
public Boolean getBoolean2() {
return Boolean.FALSE;
}
public List<String> getListString() {
return Arrays.asList(new String[] {"Tom", "Jerry"});
}
public List<User> getUsers() {
return Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")});
}
public void sayHello() {
logger.info("hello prety");
}
}
public static class IHelloRpcServiceMock implements IHelloRpcService {
public IHelloRpcServiceMock() {}
public String getSomething() {
return "somethingmock";
}
public String getSomething2() {
return "something2mock";
}
public String getSomething3() {
return "something3mock";
}
public String getSomething4() {
return "something4mock";
}
public List<String> getListString() {
return Arrays.asList(new String[] {"Tommock", "Jerrymock"});
}
public List<User> getUsers() {
return Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")});
}
public int getInt1() {
return 1;
}
public boolean getBoolean1() {
return false;
}
public Boolean getBoolean2() {
return Boolean.FALSE;
}
public void sayHello() {
logger.info("hello prety");
}
}
public static class User {
private int id;
private String name;
public User() {}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.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.rpc.cluster.support.wrapper;
public class MyMockException extends RuntimeException {
private static final long serialVersionUID = 2851692379597990457L;
public MyMockException(String message) {
super(message);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.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.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.SCOPE_KEY;
class ScopeClusterInvokerTest {
private final List<Invoker<DemoService>> invokers = new ArrayList<>();
private final Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
private final ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private final List<Exporter<?>> exporters = new ArrayList<>();
@BeforeEach
void beforeMonth() {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
}
@AfterEach
void after() throws Exception {
for (Exporter<?> exporter : exporters) {
exporter.unexport();
}
exporters.clear();
for (Invoker<DemoService> invoker : invokers) {
invoker.destroy();
if (invoker instanceof ScopeClusterInvoker) {
Assertions.assertTrue(((ScopeClusterInvoker) invoker).isDestroyed());
}
}
invokers.clear();
}
@Test
void testScopeNull_RemoteInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething1");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething1", ret.getValue());
}
@Test
void testScopeNull_LocalInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
exporters.add(exporter);
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething2");
invocation.setParameterTypes(new Class[] {});
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething2", ret.getValue());
}
@Test
void testScopeRemoteInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.addParameter(SCOPE_KEY, "remote");
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
exporters.add(exporter);
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething3");
invocation.setParameterTypes(new Class[] {});
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething3", ret.getValue());
}
@Test
void testScopeLocalInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.addParameter(SCOPE_KEY, SCOPE_LOCAL);
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething4");
invocation.setParameterTypes(new Class[] {});
Assertions.assertFalse(cluster.isAvailable(), "");
RpcInvocation finalInvocation = invocation;
Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation));
URL injvmUrl =
URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName());
injvmUrl = injvmUrl.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL)
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
exporters.add(exporter);
invocation = new RpcInvocation();
invocation.setMethodName("doSomething4");
invocation.setParameterTypes(new Class[] {});
Assertions.assertTrue(cluster.isAvailable(), "");
Result ret2 = cluster.invoke(invocation);
Assertions.assertEquals("doSomething4", ret2.getValue());
}
@Test
void testInjvmRefer() {
URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
exporters.add(exporter);
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething5");
invocation.setParameterTypes(new Class[] {});
Assertions.assertTrue(cluster.isAvailable(), "");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething5", ret.getValue());
}
@Test
void testListenUnExport() throws NoSuchFieldException, IllegalAccessException {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.addParameter(SCOPE_KEY, "local");
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
exporter.unexport();
Assertions.assertTrue(cluster instanceof ScopeClusterInvoker);
Field injvmInvoker = cluster.getClass().getDeclaredField("injvmInvoker");
injvmInvoker.setAccessible(true);
Assertions.assertNull(injvmInvoker.get(cluster));
Field isExported = cluster.getClass().getDeclaredField("isExported");
isExported.setAccessible(true);
Assertions.assertFalse(((AtomicBoolean) isExported.get(cluster)).get());
}
@Test
void testPeerInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
Map<String, Object> peer = new HashMap<>();
peer.put(PEER_KEY, true);
url = url.addAttributes(peer);
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething6");
invocation.setParameterTypes(new Class[] {});
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething6", ret.getValue());
}
@Test
void testInjvmUrlInvoke() {
URL url = URL.valueOf("injvm://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething7");
invocation.setParameterTypes(new Class[] {});
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething7", ret.getValue());
}
@Test
void testDynamicInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething8");
invocation.setParameterTypes(new Class[] {});
Result ret1 = cluster.invoke(invocation);
Assertions.assertEquals("doSomething8", ret1.getValue());
RpcContext.getServiceContext().setLocalInvoke(true);
invocation = new RpcInvocation();
invocation.setMethodName("doSomething8");
invocation.setParameterTypes(new Class[] {});
RpcInvocation finalInvocation = invocation;
Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation));
URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl));
exporters.add(exporter);
invocation = new RpcInvocation();
invocation.setMethodName("doSomething8");
invocation.setParameterTypes(new Class[] {});
Result ret2 = cluster.invoke(invocation);
Assertions.assertEquals("doSomething8", ret2.getValue());
RpcContext.getServiceContext().setLocalInvoke(false);
invocation = new RpcInvocation();
invocation.setMethodName("doSomething8");
invocation.setParameterTypes(new Class[] {});
Result ret3 = cluster.invoke(invocation);
Assertions.assertEquals("doSomething8", ret3.getValue());
}
@Test
void testBroadcast() {
URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName());
url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName()));
url = url.addParameter("cluster", "broadcast");
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
Invoker<DemoService> cluster = getClusterInvoker(url);
invokers.add(cluster);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("doSomething8");
invocation.setParameterTypes(new Class[] {});
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("doSomething8", ret.getValue());
}
private Invoker<DemoService> getClusterInvoker(URL url) {
final URL durl = url.addParameter("proxy", "jdk");
invokers.clear();
ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk");
Invoker<DemoService> invoker1 = proxy.getInvoker(new DemoServiceImpl(), DemoService.class, durl);
invokers.add(invoker1);
StaticDirectory<DemoService> dic = new StaticDirectory<>(durl, invokers, null);
dic.buildRouterChain();
AbstractClusterInvoker<DemoService> cluster = new AbstractClusterInvoker(dic) {
@Override
protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance)
throws RpcException {
if (durl.getParameter("invoke_return_error", false)) {
throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception");
} else {
return ((Invoker<?>) invokers.get(0)).invoke(invocation);
}
}
};
ScopeClusterInvoker<DemoService> demoServiceScopeClusterInvoker = new ScopeClusterInvoker<>(dic, cluster);
Assertions.assertNotNull(demoServiceScopeClusterInvoker.getDirectory());
Assertions.assertNotNull(demoServiceScopeClusterInvoker.getInvoker());
return demoServiceScopeClusterInvoker;
}
public static interface DemoService {
String doSomething1();
String doSomething2();
String doSomething3();
String doSomething4();
String doSomething5();
String doSomething6();
String doSomething7();
String doSomething8();
}
public static class DemoServiceImpl implements DemoService {
@Override
public String doSomething1() {
return "doSomething1";
}
@Override
public String doSomething2() {
return "doSomething2";
}
@Override
public String doSomething3() {
return "doSomething3";
}
@Override
public String doSomething4() {
return "doSomething4";
}
@Override
public String doSomething5() {
return "doSomething5";
}
@Override
public String doSomething6() {
return "doSomething6";
}
@Override
public String doSomething7() {
return "doSomething7";
}
@Override
public String doSomething8() {
return "doSomething8";
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.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.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.support.MockProtocol;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
class MockClusterInvokerTest {
private static final Logger logger = LoggerFactory.getLogger(MockClusterInvokerTest.class);
List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>();
@BeforeEach
public void beforeMethod() {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
invokers.clear();
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerInvoke_normal() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName());
url = url.addParameter(
REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail"));
Invoker<IHelloService> cluster = getClusterInvoker(url);
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa");
Protocol protocol = new MockProtocol();
Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
invokers.add(mInvoker1);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("something", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerInvoke_failmock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return null"))
.addParameter("invoke_return_error", "true");
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName())
.addParameter("mock", "fail:return null")
.addParameter("getSomething.mock", "return aa")
.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()))
.addParameter("invoke_return_error", "true");
Protocol protocol = new MockProtocol();
Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("aa", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
/**
* Test if mock policy works fine: force-mock
*/
@Test
void testMockInvokerInvoke_forcemock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force:return null"));
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName())
.addParameter("mock", "force:return null")
.addParameter("getSomething.mock", "return aa")
.addParameter("getSomething3xx.mock", "return xx")
.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName()));
Protocol protocol = new MockProtocol();
Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("aa", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
@Test
void testMockInvokerInvoke_forcemock_defaultreturn() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force"));
Invoker<IHelloService> cluster = getClusterInvoker(url);
URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()
+ "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ")
.addParameters(url.getParameters());
Protocol protocol = new MockProtocol();
Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
invokers.add(mInvoker1);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
Result ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_someMethods() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
+ "&" + "getSomething.mock=fail:return x"
+ "&" + "getSomething2.mock=force:return y"));
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("something", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
Assertions.assertEquals("something3", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_WithOutDefault() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
+ "&" + "getSomething.mock=fail:return x"
+ "&" + "getSomething2.mock=fail:return y"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
try {
ret = cluster.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
}
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_WithDefault() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
+ "&" + "mock" + "=" + "fail:return null"
+ "&" + "getSomething.mock" + "=" + "fail:return x"
+ "&" + "getSomething2.mock" + "=" + "fail:return y"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertNull(ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
+ "&" + "mock=fail:return z"
+ "&" + "getSomething.mock=fail:return x"
+ "&" + "getSomething2.mock=force:return y"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
Assertions.assertEquals("z", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertEquals("z", ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName()
+ "&" + "mock=force:return z"
+ "&" + "getSomething.mock=fail:return x"
+ "&" + "getSomething2.mock=force:return y"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("y", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
ret = cluster.invoke(invocation);
Assertions.assertEquals("z", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertEquals("z", ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_Fock_Default() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return x"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething2");
ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_checkCompatible_return() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=return x"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("x", ret.getValue());
// If no mock was configured, return null directly
invocation = new RpcInvocation();
invocation.setMethodName("getSomething3");
try {
ret = cluster.invoke(invocation);
Assertions.fail("fail invoke");
} catch (RpcException e) {
}
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(
PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=true" + "&" + "proxy=jdk"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("somethingmock", ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("somethingmock", ret.getValue());
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force"));
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals("somethingmock", ret.getValue());
}
@Test
void testMockInvokerFromOverride_Invoke_check_String() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("getSomething.mock", "force:return 1688")
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getSomething.mock=force:return 1688"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assertions.assertTrue(
ret.getValue() instanceof String,
"result type must be String but was : " + ret.getValue().getClass());
Assertions.assertEquals("1688", ret.getValue());
}
@Test
void testMockInvokerFromOverride_Invoke_check_int() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getInt1.mock=force:return 1688"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getInt1");
Result ret = cluster.invoke(invocation);
Assertions.assertTrue(
ret.getValue() instanceof Integer,
"result type must be integer but was : " + ret.getValue().getClass());
Assertions.assertEquals(new Integer(1688), (Integer) ret.getValue());
}
@Test
void testMockInvokerFromOverride_Invoke_check_boolean() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getBoolean1.mock=force:return true"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean1");
Result ret = cluster.invoke(invocation);
Assertions.assertTrue(
ret.getValue() instanceof Boolean,
"result type must be Boolean but was : " + ret.getValue().getClass());
Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString()));
}
@Test
void testMockInvokerFromOverride_Invoke_check_Boolean() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getBoolean2.mock=force:return true"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
Result ret = cluster.invoke(invocation);
Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString()));
}
@SuppressWarnings("unchecked")
@Test
void testMockInvokerFromOverride_Invoke_check_ListString_empty() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getListString.mock=force:return empty"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getListString");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals(0, ((List<String>) ret.getValue()).size());
}
@SuppressWarnings("unchecked")
@Test
void testMockInvokerFromOverride_Invoke_check_ListString() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getListString.mock=force:return [\"hi\",\"hi2\"]"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getListString");
Result ret = cluster.invoke(invocation);
List<String> rl = (List<String>) ret.getValue();
Assertions.assertEquals(2, rl.size());
Assertions.assertEquals("hi", rl.get(0));
}
@SuppressWarnings("unchecked")
@Test
void testMockInvokerFromOverride_Invoke_check_ListPojo_empty() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getUsers.mock=force:return empty"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsers");
Result ret = cluster.invoke(invocation);
Assertions.assertEquals(0, ((List<User>) ret.getValue()).size());
}
@Test
void testMockInvokerFromOverride_Invoke_check_ListPojoAsync() throws ExecutionException, InterruptedException {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsersAsync.mock=force"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsersAsync");
invocation.setReturnType(CompletableFuture.class);
Result ret = cluster.invoke(invocation);
CompletableFuture<List<User>> cf = null;
try {
cf = (CompletableFuture<List<User>>) ret.recreate();
} catch (Throwable e) {
e.printStackTrace();
}
Assertions.assertEquals(2, cf.get().size());
Assertions.assertEquals("Tommock", cf.get().get(0).getName());
}
@SuppressWarnings("unchecked")
@Test
void testMockInvokerFromOverride_Invoke_check_ListPojo() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getUsers.mock=force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsers");
Result ret = cluster.invoke(invocation);
List<User> rl = (List<User>) ret.getValue();
Assertions.assertEquals(2, rl.size());
Assertions.assertEquals("hi1", rl.get(0).getName());
}
@Test
void testMockInvokerFromOverride_Invoke_check_ListPojo_error() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getUsers.mock=force:return [{id:x, name:\"hi1\"}]"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsers");
try {
cluster.invoke(invocation);
} catch (RpcException e) {
}
}
@Test
void testMockInvokerFromOverride_Invoke_force_throw() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(
PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:throw "))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
Assertions.assertFalse(e.isBiz(), "not custom exception");
}
}
@Test
void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(
PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getBoolean2.mock=force:throw org.apache.dubbo.rpc.cluster.support.wrapper.MyMockException"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation).recreate();
Assertions.fail();
} catch (MyMockException e) {
}
}
@Test
void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&"
+ "getBoolean2.mock=force:throw java.lang.RuntimeException2"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e.getCause() instanceof IllegalStateException);
}
}
@Test
void testMockInvokerFromOverride_Invoke_mock_false() {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.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.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.filter.DemoService;
import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AbstractClusterTest {
@Test
void testBuildClusterInvokerChain() {
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put(REFERENCE_FILTER_KEY, "demo");
ServiceConfigURL url = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
URL consumerUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters);
consumerUrl = consumerUrl.setScopeModel(ApplicationModel.defaultModel().getInternalModule());
Directory<?> directory = mock(Directory.class);
when(directory.getUrl()).thenReturn(url);
when(directory.getConsumerUrl()).thenReturn(consumerUrl);
DemoCluster demoCluster = new DemoCluster();
Invoker<?> invoker = demoCluster.join(directory, true);
Assertions.assertTrue(invoker instanceof AbstractCluster.ClusterFilterInvoker);
Assertions.assertTrue(
((AbstractCluster.ClusterFilterInvoker<?>) invoker).getFilterInvoker()
instanceof FilterChainBuilder.ClusterCallbackRegistrationInvoker);
}
static class DemoCluster extends AbstractCluster {
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
return super.join(directory, buildFilterChain);
}
@Override
protected <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new DemoAbstractClusterInvoker<>(directory, directory.getUrl());
}
}
static class DemoAbstractClusterInvoker<T> extends AbstractClusterInvoker<T> {
@Override
public URL getUrl() {
return super.getUrl();
}
public DemoAbstractClusterInvoker(Directory<T> directory, URL url) {
super(directory, url);
}
@Override
protected Result doInvoke(Invocation invocation, List list, LoadBalance loadbalance) throws RpcException {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.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.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(
value = "demo",
group = {CONSUMER})
public class DemoClusterFilter implements ClusterFilter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.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.rpc.cluster.support.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE_FORCE;
import static org.apache.dubbo.common.constants.RegistryConstants.ZONE_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class ZoneAwareClusterInvokerTest {
private Directory directory = mock(Directory.class);
private ClusterInvoker firstInvoker = mock(ClusterInvoker.class);
private ClusterInvoker secondInvoker = mock(ClusterInvoker.class);
private ClusterInvoker thirdInvoker = mock(ClusterInvoker.class);
private Invocation invocation = mock(Invocation.class);
private ZoneAwareClusterInvoker<ZoneAwareClusterInvokerTest> zoneAwareClusterInvoker;
private URL url = URL.valueOf("test://test");
private URL registryUrl = URL.valueOf("localhost://test");
String expectedValue = "expected";
String unexpectedValue = "unexpected";
@Test
void testPreferredStrategy() {
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
firstInvoker = newUnexpectedInvoker();
thirdInvoker = newUnexpectedInvoker();
secondInvoker = (ClusterInvoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url;
}
if ("getRegistryUrl".equals(method.getName())) {
return registryUrl.addParameter(PREFERRED_KEY, true);
}
if ("isAvailable".equals(method.getName())) {
return true;
}
if ("invoke".equals(method.getName())) {
return new AppResponse(expectedValue);
}
return null;
});
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
add(thirdInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory);
AppResponse response = (AppResponse) zoneAwareClusterInvoker.invoke(invocation);
Assertions.assertEquals(expectedValue, response.getValue());
}
@Test
void testRegistryZoneStrategy() {
String zoneKey = "zone";
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey);
firstInvoker = newUnexpectedInvoker();
thirdInvoker = newUnexpectedInvoker();
secondInvoker = (ClusterInvoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url;
}
if ("getRegistryUrl".equals(method.getName())) {
return registryUrl.addParameter(ZONE_KEY, zoneKey);
}
if ("isAvailable".equals(method.getName())) {
return true;
}
if ("invoke".equals(method.getName())) {
return new AppResponse(expectedValue);
}
return null;
});
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
add(thirdInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory);
AppResponse response = (AppResponse) zoneAwareClusterInvoker.invoke(invocation);
Assertions.assertEquals(expectedValue, response.getValue());
}
@Test
void testRegistryZoneForceStrategy() {
String zoneKey = "zone";
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {});
given(invocation.getArguments()).willReturn(new Object[] {});
given(invocation.getObjectAttachments()).willReturn(new HashMap<>());
RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey);
RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE_FORCE, "true");
firstInvoker = newUnexpectedInvoker();
secondInvoker = newUnexpectedInvoker();
thirdInvoker = newUnexpectedInvoker();
given(directory.list(invocation)).willReturn(new ArrayList() {
{
add(firstInvoker);
add(secondInvoker);
add(thirdInvoker);
}
});
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory);
Assertions.assertThrows(IllegalStateException.class, () -> zoneAwareClusterInvoker.invoke(invocation));
}
@Test
public void testNoAvailableInvoker() {
given(directory.getUrl()).willReturn(url);
given(directory.getConsumerUrl()).willReturn(url);
given(directory.list(invocation)).willReturn(new ArrayList<>(0));
given(directory.getInterface()).willReturn(ZoneAwareClusterInvokerTest.class);
zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory);
Assertions.assertThrows(RpcException.class, () -> zoneAwareClusterInvoker.invoke(invocation));
}
private ClusterInvoker newUnexpectedInvoker() {
return (ClusterInvoker) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> {
if ("getUrl".equals(method.getName())) {
return url;
}
if ("getRegistryUrl".equals(method.getName())) {
return registryUrl;
}
if ("isAvailable".equals(method.getName())) {
return true;
}
if ("invoke".equals(method.getName())) {
return new AppResponse(unexpectedValue);
}
return null;
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceMock.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceMock.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.rpc.cluster.filter;
class DemoServiceMock implements DemoService {
public String sayHello(String name) {
return name;
}
public int plus(int a, int b) {
return a + b;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.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.rpc.cluster.filter;
class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return name;
}
@Override
public int plus(int a, int b) {
return 0;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.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.rpc.cluster.filter;
public interface DemoService {
String sayHello(String name);
int plus(int a, int b);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.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.rpc.cluster.filter;
class DemoServiceLocal implements DemoService {
public DemoServiceLocal(DemoService demoService) {}
public String sayHello(String name) {
return name;
}
public int plus(int a, int b) {
return a + b;
}
public void ondisconnect() {}
public void onconnect() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockService.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockService.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.rpc.cluster.filter;
class MockService implements DemoService {
public String sayHello(String name) {
return name;
}
public int plus(int a, int b) {
return a + b;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.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.rpc.cluster.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(group = CONSUMER, value = "log")
public class LogFilter implements Filter, Filter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.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.rpc.cluster.filter;
class DemoServiceStub implements DemoService {
public DemoServiceStub(DemoService demoService) {}
public String sayHello(String name) {
return name;
}
public int plus(int a, int b) {
return a + b;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.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.rpc.cluster.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.protocol.AbstractInvoker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
class DefaultFilterChainBuilderTest {
@Test
void testBuildInvokerChainForLocalReference() {
DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder();
// verify that no filter is built by default
URL urlWithoutFilter =
URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName());
urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel());
AbstractInvoker<DemoService> invokerWithoutFilter =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutFilter) {
@Override
protected Result doInvoke(Invocation invocation) {
return null;
}
};
Invoker<?> invokerAfterBuild =
defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER);
// verify that if LogFilter is configured, LogFilter should exist in the filter chain
URL urlWithFilter = URL.valueOf("injvm://127.0.0.1/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(REFERENCE_FILTER_KEY, "log");
urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel());
AbstractInvoker<DemoService> invokerWithFilter =
new AbstractInvoker<DemoService>(DemoService.class, urlWithFilter) {
@Override
protected Result doInvoke(Invocation invocation) {
return null;
}
};
invokerAfterBuild =
defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER);
Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker);
}
@Test
void testBuildInvokerChainForRemoteReference() {
DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder();
// verify that no filter is built by default
URL urlWithoutFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName());
urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel());
AbstractInvoker<DemoService> invokerWithoutFilter =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutFilter) {
@Override
protected Result doInvoke(Invocation invocation) {
return null;
}
};
Invoker<?> invokerAfterBuild =
defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER);
// Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker);
// verify that if LogFilter is configured, LogFilter should exist in the filter chain
URL urlWithFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(REFERENCE_FILTER_KEY, "log");
urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel());
AbstractInvoker<DemoService> invokerWithFilter =
new AbstractInvoker<DemoService>(DemoService.class, urlWithFilter) {
@Override
protected Result doInvoke(Invocation invocation) {
return null;
}
};
invokerAfterBuild =
defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER);
Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.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.rpc.cluster.directory;
import org.apache.dubbo.rpc.AttachmentsAdapter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
class MockDirInvocation implements Invocation {
private Map<String, Object> attachments;
public MockDirInvocation() {
attachments = new HashMap<>();
attachments.put(PATH_KEY, "dubbo");
attachments.put(GROUP_KEY, "dubbo");
attachments.put(VERSION_KEY, "1.0.0");
attachments.put(DUBBO_VERSION_KEY, "1.0.0");
attachments.put(TOKEN_KEY, "sfag");
attachments.put(TIMEOUT_KEY, "1000");
}
@Override
public String getTargetServiceUniqueName() {
return null;
}
@Override
public String getProtocolServiceKey() {
return null;
}
public String getMethodName() {
return "echo";
}
@Override
public String getServiceName() {
return "DemoService";
}
public Class<?>[] getParameterTypes() {
return new Class[] {String.class};
}
public Object[] getArguments() {
return new Object[] {"aa"};
}
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(attachments);
}
@Override
public Map<String, Object> getObjectAttachments() {
return attachments;
}
@Override
public Map<String, Object> copyObjectAttachments() {
return new HashMap<>(attachments);
}
@Override
public void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) {
attachments.entrySet().forEach(consumer);
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
attachments.put(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, String value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, Object value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setObjectAttachmentIfAbsent(String key, Object value) {
attachments.putIfAbsent(key, value);
}
public Invoker<?> getInvoker() {
return null;
}
@Override
public Object put(Object key, Object value) {
return null;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public void setServiceModel(ServiceModel serviceModel) {}
@Override
public ServiceModel getServiceModel() {
return null;
}
@Override
public Map<Object, Object> getAttributes() {
return null;
}
public String getAttachment(String key) {
return (String) getObjectAttachment(key);
}
@Override
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
public String getAttachment(String key, String defaultValue) {
return (String) getObjectAttachment(key, defaultValue);
}
@Override
public void addInvokedInvoker(Invoker<?> invoker) {}
@Override
public List<Invoker<?>> getInvokedInvokers() {
return null;
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
Object result = attachments.get(key);
if (result == null) {
return defaultValue;
}
return result;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.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.rpc.cluster.directory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
class StaticDirectoryTest {
private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService");
private URL getRouteUrl(String rule) {
return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule);
}
@Test
void testStaticDirectory() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost()));
List<StateRouter> routers = new ArrayList<StateRouter>();
routers.add(router);
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 =
new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"), true);
Invoker<String> invoker2 = new MockInvoker<String>(
URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true);
Invoker<String> invoker3 = new MockInvoker<String>(
URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
StaticDirectory<String> staticDirectory = new StaticDirectory<>(filteredInvokers);
boolean isAvailable = staticDirectory.isAvailable();
Assertions.assertTrue(isAvailable);
List<Invoker<String>> newInvokers = staticDirectory.list(new MockDirInvocation());
Assertions.assertTrue(newInvokers.size() > 0);
staticDirectory.destroy();
Assertions.assertEquals(0, staticDirectory.getInvokers().size());
Assertions.assertEquals(0, staticDirectory.getValidInvokers().size());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class DoubleSumMerger implements Merger<Double> {
@Override
public Double merge(Double... items) {
return Arrays.stream(items)
.filter(Objects::nonNull)
.mapToDouble(Double::doubleValue)
.sum();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class IntSumMerger implements Merger<Integer> {
@Override
public Integer merge(Integer... items) {
return Arrays.stream(items)
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.sum();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class LongSumMerger implements Merger<Long> {
@Override
public Long merge(Long... items) {
return Arrays.stream(items)
.filter(Objects::nonNull)
.mapToLong(Long::longValue)
.sum();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindAnyMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindAnyMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
public class IntFindAnyMerger implements Merger<Integer> {
@Override
public Integer merge(Integer... items) {
return Arrays.stream(items).findAny().orElse(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Array;
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 java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ResultMergerTest {
private MergerFactory mergerFactory;
@BeforeEach
public void setup() {
mergerFactory = new MergerFactory();
mergerFactory.setScopeModel(ApplicationModel.defaultModel());
}
/**
* MergerFactory test
*/
@Test
void testMergerFactoryIllegalArgumentException() {
try {
mergerFactory.getMerger(null);
Assertions.fail("expected IllegalArgumentException for null argument");
} catch (IllegalArgumentException exception) {
Assertions.assertEquals("returnType is null", exception.getMessage());
}
}
/**
* ArrayMerger test
*/
@Test
void testArrayMergerIllegalArgumentException() {
String[] stringArray = {"1", "2", "3"};
Integer[] integerArray = {3, 4, 5};
try {
Object result = ArrayMerger.INSTANCE.merge(stringArray, null, integerArray);
Assertions.fail("expected IllegalArgumentException for different arguments' types");
} catch (IllegalArgumentException exception) {
Assertions.assertEquals("Arguments' types are different", exception.getMessage());
}
}
/**
* ArrayMerger test
*/
@Test
void testArrayMerger() {
String[] stringArray1 = {"1", "2", "3"};
String[] stringArray2 = {"4", "5", "6"};
String[] stringArray3 = {};
Object result = ArrayMerger.INSTANCE.merge(stringArray1, stringArray2, stringArray3, null);
Assertions.assertTrue(result.getClass().isArray());
Assertions.assertEquals(6, Array.getLength(result));
Assertions.assertTrue(String.class.isInstance(Array.get(result, 0)));
for (int i = 0; i < 6; i++) {
Assertions.assertEquals(String.valueOf(i + 1), Array.get(result, i));
}
Integer[] intArray1 = {1, 2, 3};
Integer[] intArray2 = {4, 5, 6};
Integer[] intArray3 = {7};
// trigger ArrayMerger
result = mergerFactory.getMerger(Integer[].class).merge(intArray1, intArray2, intArray3, null);
Assertions.assertTrue(result.getClass().isArray());
Assertions.assertEquals(7, Array.getLength(result));
Assertions.assertSame(Integer.class, result.getClass().getComponentType());
for (int i = 0; i < 7; i++) {
Assertions.assertEquals(i + 1, Array.get(result, i));
}
result = ArrayMerger.INSTANCE.merge(null);
Assertions.assertEquals(0, Array.getLength(result));
result = ArrayMerger.INSTANCE.merge(null, null);
Assertions.assertEquals(0, Array.getLength(result));
result = ArrayMerger.INSTANCE.merge(null, new Object[0]);
Assertions.assertEquals(0, Array.getLength(result));
}
/**
* BooleanArrayMerger test
*/
@Test
void testBooleanArrayMerger() {
boolean[] arrayOne = {true, false};
boolean[] arrayTwo = {false};
boolean[] result = mergerFactory.getMerger(boolean[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(3, result.length);
boolean[] mergedResult = {true, false, false};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i]);
}
result = mergerFactory.getMerger(boolean[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(boolean[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* ByteArrayMerger test
*/
@Test
void testByteArrayMerger() {
byte[] arrayOne = {1, 2};
byte[] arrayTwo = {1, 32};
byte[] result = mergerFactory.getMerger(byte[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
byte[] mergedResult = {1, 2, 1, 32};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i]);
}
result = mergerFactory.getMerger(byte[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(byte[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* CharArrayMerger test
*/
@Test
void testCharArrayMerger() {
char[] arrayOne = "hello".toCharArray();
char[] arrayTwo = "world".toCharArray();
char[] result = mergerFactory.getMerger(char[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(10, result.length);
char[] mergedResult = "helloworld".toCharArray();
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i]);
}
result = mergerFactory.getMerger(char[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(char[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* DoubleArrayMerger test
*/
@Test
void testDoubleArrayMerger() {
double[] arrayOne = {1.2d, 3.5d};
double[] arrayTwo = {2d, 34d};
double[] result = mergerFactory.getMerger(double[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
double[] mergedResult = {1.2d, 3.5d, 2d, 34d};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i], 0.0);
}
result = mergerFactory.getMerger(double[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(double[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* FloatArrayMerger test
*/
@Test
void testFloatArrayMerger() {
float[] arrayOne = {1.2f, 3.5f};
float[] arrayTwo = {2f, 34f};
float[] result = mergerFactory.getMerger(float[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
double[] mergedResult = {1.2f, 3.5f, 2f, 34f};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i], 0.0);
}
result = mergerFactory.getMerger(float[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(float[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* IntArrayMerger test
*/
@Test
void testIntArrayMerger() {
int[] arrayOne = {1, 2};
int[] arrayTwo = {2, 34};
int[] result = mergerFactory.getMerger(int[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
double[] mergedResult = {1, 2, 2, 34};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i], 0.0);
}
result = mergerFactory.getMerger(int[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(int[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* ListMerger test
*/
@Test
void testListMerger() {
List<Object> list1 = new ArrayList<Object>() {
{
add(null);
add("1");
add("2");
}
};
List<Object> list2 = new ArrayList<Object>() {
{
add("3");
add("4");
}
};
List result = mergerFactory.getMerger(List.class).merge(list1, list2, null);
Assertions.assertEquals(5, result.size());
ArrayList<String> expected = new ArrayList<String>() {
{
add(null);
add("1");
add("2");
add("3");
add("4");
}
};
Assertions.assertEquals(expected, result);
result = mergerFactory.getMerger(List.class).merge(null);
Assertions.assertEquals(0, result.size());
result = mergerFactory.getMerger(List.class).merge(null, null);
Assertions.assertEquals(0, result.size());
}
/**
* LongArrayMerger test
*/
@Test
void testMapArrayMerger() {
Map<Object, Object> mapOne = new HashMap<Object, Object>() {
{
put("11", 222);
put("223", 11);
}
};
Map<Object, Object> mapTwo = new HashMap<Object, Object>() {
{
put("3333", 3232);
put("444", 2323);
}
};
Map<Object, Object> result = mergerFactory.getMerger(Map.class).merge(mapOne, mapTwo, null);
Assertions.assertEquals(4, result.size());
Map<String, Integer> mergedResult = new HashMap<String, Integer>() {
{
put("11", 222);
put("223", 11);
put("3333", 3232);
put("444", 2323);
}
};
Assertions.assertEquals(mergedResult, result);
result = mergerFactory.getMerger(Map.class).merge(null);
Assertions.assertEquals(0, result.size());
result = mergerFactory.getMerger(Map.class).merge(null, null);
Assertions.assertEquals(0, result.size());
}
/**
* LongArrayMerger test
*/
@Test
void testLongArrayMerger() {
long[] arrayOne = {1L, 2L};
long[] arrayTwo = {2L, 34L};
long[] result = mergerFactory.getMerger(long[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
double[] mergedResult = {1L, 2L, 2L, 34L};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i], 0.0);
}
result = mergerFactory.getMerger(long[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(long[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* SetMerger test
*/
@Test
void testSetMerger() {
Set<Object> set1 = new HashSet<Object>() {
{
add(null);
add("1");
add("2");
}
};
Set<Object> set2 = new HashSet<Object>() {
{
add("2");
add("3");
}
};
Set result = mergerFactory.getMerger(Set.class).merge(set1, set2, null);
Assertions.assertEquals(4, result.size());
Assertions.assertEquals(
new HashSet<String>() {
{
add(null);
add("1");
add("2");
add("3");
}
},
result);
result = mergerFactory.getMerger(Set.class).merge(null);
Assertions.assertEquals(0, result.size());
result = mergerFactory.getMerger(Set.class).merge(null, null);
Assertions.assertEquals(0, result.size());
}
/**
* ShortArrayMerger test
*/
@Test
void testShortArrayMerger() {
short[] arrayOne = {1, 2};
short[] arrayTwo = {2, 34};
short[] result = mergerFactory.getMerger(short[].class).merge(arrayOne, arrayTwo, null);
Assertions.assertEquals(4, result.length);
double[] mergedResult = {1, 2, 2, 34};
for (int i = 0; i < mergedResult.length; i++) {
Assertions.assertEquals(mergedResult[i], result[i], 0.0);
}
result = mergerFactory.getMerger(short[].class).merge(null);
Assertions.assertEquals(0, result.length);
result = mergerFactory.getMerger(short[].class).merge(null, null);
Assertions.assertEquals(0, result.length);
}
/**
* IntSumMerger test
*/
@Test
void testIntSumMerger() {
Integer[] intArr = IntStream.rangeClosed(1, 100).boxed().toArray(Integer[]::new);
Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intsum");
Assertions.assertEquals(5050, merger.merge(intArr));
intArr = new Integer[] {};
Assertions.assertEquals(0, merger.merge(intArr));
}
/**
* DoubleSumMerger test
*/
@Test
void testDoubleSumMerger() {
Double[] doubleArr =
DoubleStream.iterate(1, v -> ++v).limit(100).boxed().toArray(Double[]::new);
Merger<Double> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "doublesum");
Assertions.assertEquals(5050, merger.merge(doubleArr));
doubleArr = new Double[] {};
Assertions.assertEquals(0, merger.merge(doubleArr));
}
/**
* FloatSumMerger test
*/
@Test
void testFloatSumMerger() {
Float[] floatArr = Stream.iterate(1.0F, v -> ++v).limit(100).toArray(Float[]::new);
Merger<Float> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "floatsum");
Assertions.assertEquals(5050, merger.merge(floatArr));
floatArr = new Float[] {};
Assertions.assertEquals(0, merger.merge(floatArr));
}
/**
* LongSumMerger test
*/
@Test
void testLongSumMerger() {
Long[] longArr = LongStream.rangeClosed(1, 100).boxed().toArray(Long[]::new);
Merger<Long> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "longsum");
Assertions.assertEquals(5050, merger.merge(longArr));
longArr = new Long[] {};
Assertions.assertEquals(0, merger.merge(longArr));
}
/**
* IntFindAnyMerger test
*/
@Test
void testIntFindAnyMerger() {
Integer[] intArr = {1, 2, 3, 4};
Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intany");
Assertions.assertNotNull(merger.merge(intArr));
intArr = new Integer[] {};
Assertions.assertNull(merger.merge(intArr));
}
/**
* IntFindFirstMerger test
*/
@Test
void testIntFindFirstMerger() {
Integer[] intArr = {1, 2, 3, 4};
Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intfirst");
Assertions.assertEquals(1, merger.merge(intArr));
intArr = new Integer[] {};
Assertions.assertNull(merger.merge(intArr));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindFirstMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindFirstMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
public class IntFindFirstMerger implements Merger<Integer> {
@Override
public Integer merge(Integer... items) {
return Arrays.stream(items).findFirst().orElse(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.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.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class FloatSumMerger implements Merger<Float> {
@Override
public Float merge(Float... items) {
return Arrays.stream(items).filter(Objects::nonNull).reduce(0.0F, (f1, f2) -> f1 + f2);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.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.rpc.cluster.configurator.consts;
/**
* test case url constant
*/
public class UrlConstant {
public static final String URL_CONSUMER =
"dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&side=consumer";
public static final String URL_ONE =
"dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&timeout=1000&side=consumer";
public static final String APPLICATION_BAR_SIDE_CONSUMER_11 =
"dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&side=consumer";
public static final String TIMEOUT_1000_SIDE_CONSUMER_11 =
"dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer";
public static final String SERVICE_TIMEOUT_200 = "override://10.20.153.10/com.foo.BarService?timeout=200";
public static final String APPLICATION_BAR_SIDE_CONSUMER_10 =
"dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&side=consumer";
public static final String TIMEOUT_1000_SIDE_CONSUMER_10 =
"dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.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.rpc.cluster.configurator.absent;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class AbsentConfiguratorTest {
@Test
void testOverrideApplication() {
AbsentConfigurator configurator =
new AbsentConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
Assertions.assertEquals("1000", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11));
Assertions.assertNull(url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11));
Assertions.assertEquals("1000", url.getParameter("timeout"));
}
@Test
void testOverrideHost() {
AbsentConfigurator configurator = new AbsentConfigurator(
URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
Assertions.assertEquals("1000", url.getParameter("timeout"));
AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf(UrlConstant.SERVICE_TIMEOUT_200));
url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10));
Assertions.assertNull(url.getParameter("timeout"));
url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10));
Assertions.assertEquals("1000", url.getParameter("timeout"));
}
// Test the version after 2.7
@Test
void testAbsentForVersion27() {
{
String consumerUrlV27 =
"dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100";
URL consumerConfiguratorUrl = URL.valueOf("absent://0.0.0.0/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "consumer");
params.put("configVersion", "2.7");
params.put("application", "foo");
params.put("timeout", "10000");
params.put("weight", "200");
consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params);
AbsentConfigurator configurator = new AbsentConfigurator(consumerConfiguratorUrl);
// Meet the configured conditions:
// same side
// The port of configuratorUrl is 0
// The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27
// same appName
URL url = configurator.configure(URL.valueOf(consumerUrlV27));
Assertions.assertEquals("100", url.getParameter("timeout"));
Assertions.assertEquals("200", url.getParameter("weight"));
}
{
String providerUrlV27 =
"dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100";
URL providerConfiguratorUrl = URL.valueOf("absent://172.24.160.179:21880/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "provider");
params.put("configVersion", "2.7");
params.put("application", "foo");
params.put("timeout", "20000");
params.put("weight", "200");
providerConfiguratorUrl = providerConfiguratorUrl.addParameters(params);
// Meet the configured conditions:
// same side
// same port
// The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as
// consumerUrlV27
// same appName
AbsentConfigurator configurator = new AbsentConfigurator(providerConfiguratorUrl);
URL url = configurator.configure(URL.valueOf(providerUrlV27));
Assertions.assertEquals("20000", url.getParameter("timeout"));
Assertions.assertEquals("100", url.getParameter("weight"));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.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.rpc.cluster.configurator.parser;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION;
class ConfigParserTest {
private String streamToString(InputStream stream) throws IOException {
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
return new String(bytes);
}
@Test
void snakeYamlBasicTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(yamlStream);
ConfiguratorConfig config = ConfiguratorConfig.parseFromMap(map);
Assertions.assertNotNull(config);
}
}
@Test
void parseConfiguratorsServiceNoAppTest() throws Exception {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(2, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1:20880", url.getAddress());
Assertions.assertEquals(222, url.getParameter(WEIGHT_KEY, 0));
}
}
@Test
void parseConfiguratorsServiceGroupVersionTest() throws Exception {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("testgroup", url.getGroup());
Assertions.assertEquals("1.0.0", url.getVersion());
}
}
@Test
void parseConfiguratorsServiceMultiAppsTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(4, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1", url.getAddress());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
Assertions.assertNotNull(url.getApplication());
}
}
@Test
void parseConfiguratorsServiceNoRuleTest() {
Assertions.assertThrows(IllegalStateException.class, () -> {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml")) {
ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.fail();
}
});
}
@Test
void parseConfiguratorsAppMultiServicesTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml")) {
String yamlFile = streamToString(yamlStream);
List<URL> urls = ConfigParser.parseConfigurators(yamlFile);
Assertions.assertNotNull(urls);
Assertions.assertEquals(4, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1", url.getAddress());
Assertions.assertEquals("service1", url.getServiceInterface());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY));
Assertions.assertEquals("demo-consumer", url.getApplication());
}
}
@Test
void parseConfiguratorsAppAnyServicesTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(2, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1", url.getAddress());
Assertions.assertEquals("*", url.getServiceInterface());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY));
Assertions.assertEquals("demo-consumer", url.getApplication());
}
}
@Test
void parseConfiguratorsAppNoServiceTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1", url.getAddress());
Assertions.assertEquals("*", url.getServiceInterface());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY));
Assertions.assertEquals("demo-consumer", url.getApplication());
}
}
@Test
void parseConsumerSpecificProvidersTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("127.0.0.1", url.getAddress());
Assertions.assertEquals("*", url.getServiceInterface());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY));
Assertions.assertEquals("127.0.0.1:20880", url.getParameter(OVERRIDE_PROVIDERS_KEY));
Assertions.assertEquals("demo-consumer", url.getApplication());
}
}
@Test
void parseProviderConfigurationV3() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("0.0.0.0", url.getAddress());
Assertions.assertEquals("*", url.getServiceInterface());
Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0));
Assertions.assertEquals("demo-provider", url.getApplication());
URL matchURL1 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1");
URL matchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService2?match_key1=value1");
URL notMatchURL1 = URL.valueOf("dubbo://10.0.0.2:20880/DemoService?match_key1=value1"); // address not match
URL notMatchURL2 =
URL.valueOf("dubbo://10.0.0.1:20880/DemoServiceNotMatch?match_key1=value1"); // service not match
URL notMatchURL3 =
URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match
ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION);
Assertions.assertTrue(matcher.isMatch(matchURL1.getAddress(), matchURL1));
Assertions.assertTrue(matcher.isMatch(matchURL2.getAddress(), matchURL2));
Assertions.assertFalse(matcher.isMatch(notMatchURL1.getAddress(), notMatchURL1));
Assertions.assertFalse(matcher.isMatch(notMatchURL2.getAddress(), notMatchURL2));
Assertions.assertFalse(matcher.isMatch(notMatchURL3.getAddress(), notMatchURL3));
}
}
@Test
void parseProviderConfigurationV3Compatibility() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Compatibility.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("10.0.0.1:20880", url.getAddress());
Assertions.assertEquals("DemoService", url.getServiceInterface());
Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0));
Assertions.assertEquals("demo-provider", url.getApplication());
URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1");
URL notMatchURL =
URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match
ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION);
Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL));
Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL));
}
}
@Test
void parseProviderConfigurationV3Conflict() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Duplicate.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("10.0.0.1:20880", url.getAddress());
Assertions.assertEquals("DemoService", url.getServiceInterface());
Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0));
Assertions.assertEquals("demo-provider", url.getApplication());
URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1");
URL notMatchURL =
URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match
ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION);
Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL));
Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL));
}
}
@Test
void parseURLJsonArrayCompatible() {
String configData =
"[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]";
List<URL> urls = ConfigParser.parseConfigurators(configData);
Assertions.assertNotNull(urls);
Assertions.assertEquals(1, urls.size());
URL url = urls.get(0);
Assertions.assertEquals("0.0.0.0", url.getAddress());
Assertions.assertEquals("com.xx.Service", url.getServiceInterface());
Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.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.rpc.cluster.configurator.override;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator;
import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ParamMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION;
class OverrideConfiguratorTest {
@Test
void testOverride_Application() {
OverrideConfigurator configurator =
new OverrideConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11));
Assertions.assertNull(url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11));
Assertions.assertEquals("1000", url.getParameter("timeout"));
}
@Test
void testOverride_Host() {
OverrideConfigurator configurator = new OverrideConfigurator(
URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200"));
URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER));
Assertions.assertEquals("200", url.getParameter("timeout"));
url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE));
Assertions.assertEquals("200", url.getParameter("timeout"));
AbsentConfigurator configurator1 =
new AbsentConfigurator(URL.valueOf("override://10.20.153.10/com.foo.BarService?timeout=200"));
url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10));
Assertions.assertNull(url.getParameter("timeout"));
url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10));
Assertions.assertEquals("1000", url.getParameter("timeout"));
}
// Test the version after 2.7
@Test
void testOverrideForVersion27() {
{
String consumerUrlV27 =
"dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100";
URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "consumer");
params.put("configVersion", "2.7");
params.put("application", "foo");
params.put("timeout", "10000");
consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params);
OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl);
// Meet the configured conditions:
// same side
// The port of configuratorUrl is 0
// The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27
// same appName
URL url = configurator.configure(URL.valueOf(consumerUrlV27));
Assertions.assertEquals(url.getParameter("timeout"), "10000");
}
{
String providerUrlV27 =
"dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100";
URL providerConfiguratorUrl = URL.valueOf("override://172.24.160.179:21880/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "provider");
params.put("configVersion", "2.7");
params.put("application", "foo");
params.put("weight", "200");
providerConfiguratorUrl = providerConfiguratorUrl.addParameters(params);
// Meet the configured conditions:
// same side
// same port
// The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as
// consumerUrlV27
// same appName
OverrideConfigurator configurator = new OverrideConfigurator(providerConfiguratorUrl);
URL url = configurator.configure(URL.valueOf(providerUrlV27));
Assertions.assertEquals(url.getParameter("weight"), "200");
}
}
// Test the version after 2.7
@Test
void testOverrideForVersion3() {
// match
{
String consumerUrlV3 =
"dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100";
URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "consumer");
params.put("configVersion", "v3.0");
params.put("application", "foo");
params.put("timeout", "10000");
ConditionMatch matcher = new ConditionMatch();
ParamMatch paramMatch = new ParamMatch();
paramMatch.setKey("match_key");
StringMatch stringMatch = new StringMatch();
stringMatch.setExact("value");
paramMatch.setValue(stringMatch);
matcher.setParam(Arrays.asList(paramMatch));
consumerConfiguratorUrl = consumerConfiguratorUrl.putAttribute(MATCH_CONDITION, matcher);
consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params);
OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl);
// Meet the configured conditions:
// same side
// The port of configuratorUrl is 0
// The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27
// same appName
URL originalURL = URL.valueOf(consumerUrlV3);
Assertions.assertEquals("100", originalURL.getParameter("timeout"));
URL url = configurator.configure(originalURL);
Assertions.assertEquals("10000", url.getParameter("timeout"));
}
// mismatch
{
String consumerUrlV3 =
"dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100";
URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService");
Map<String, String> params = new HashMap<>();
params.put("side", "consumer");
params.put("configVersion", "v3.0");
params.put("application", "foo");
params.put("timeout", "10000");
ConditionMatch matcher = new ConditionMatch();
ParamMatch paramMatch = new ParamMatch();
paramMatch.setKey("match_key");
StringMatch stringMatch = new StringMatch();
stringMatch.setExact("not_match_value");
paramMatch.setValue(stringMatch);
matcher.setParam(Arrays.asList(paramMatch));
consumerConfiguratorUrl = consumerConfiguratorUrl.putAttribute(MATCH_CONDITION, matcher);
consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params);
OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl);
// Meet the configured conditions:
// same side
// The port of configuratorUrl is 0
// The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27
// same appName
URL originalURL = URL.valueOf(consumerUrlV3);
Assertions.assertEquals("100", originalURL.getParameter("timeout"));
URL url = configurator.configure(originalURL);
Assertions.assertEquals("100", url.getParameter("timeout"));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* RandomLoadBalance Test
*/
class RandomLoadBalanceTest extends LoadBalanceBaseTest {
@Test
void testRandomLoadBalanceSelect() {
int runs = 1000;
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RandomLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
Assertions.assertTrue(
Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()),
"abs diff should < avg");
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
RpcStatus.beginCount(invokers.get(i).getUrl(), invocation.getMethodName());
}
}
counter = getInvokeCounter(runs, LeastActiveLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
}
Assertions.assertEquals(runs, counter.get(invoker1).intValue());
Assertions.assertEquals(0, counter.get(invoker2).intValue());
Assertions.assertEquals(0, counter.get(invoker3).intValue());
Assertions.assertEquals(0, counter.get(invoker4).intValue());
Assertions.assertEquals(0, counter.get(invoker5).intValue());
}
@Test
void testSelectByWeight() {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int sumInvoker3 = 0;
int loop = 10000;
RandomLoadBalance lb = new RandomLoadBalance();
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokers, null, weightTestInvocation);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
}
if (selected.getUrl().getProtocol().equals("test3")) {
sumInvoker3++;
}
}
// 1 : 9 : 6
Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.HashMap;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class AbstractLoadBalanceTest {
private AbstractLoadBalance balance = new AbstractLoadBalance() {
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
return null;
}
};
@Test
void testGetWeight() {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("say");
Invoker invoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly());
URL url1 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>());
url1 = url1.addParameter(TIMESTAMP_KEY, System.currentTimeMillis() - Integer.MAX_VALUE - 1);
given(invoker1.getUrl()).willReturn(url1);
Invoker invoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly());
URL url2 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>());
url2 = url2.addParameter(TIMESTAMP_KEY, System.currentTimeMillis() - 10 * 60 * 1000L - 1);
given(invoker2.getUrl()).willReturn(url2);
Assertions.assertEquals(balance.getWeight(invoker1, invocation), balance.getWeight(invoker2, invocation));
}
@Test
void testGetRegistryWeight() {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("say");
Invoker invoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly());
URL url1 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>());
given(invoker1.getUrl()).willReturn(url1);
ClusterInvoker invoker2 =
mock(ClusterInvoker.class, Mockito.withSettings().stubOnly());
URL url2 = new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>());
url2 = url2.addParameter(WEIGHT_KEY, 20);
URL registryUrl2 =
new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>());
registryUrl2 = registryUrl2.addParameter(WEIGHT_KEY, 30);
given(invoker2.getUrl()).willReturn(url2);
given(invoker2.getRegistryUrl()).willReturn(registryUrl2);
Assertions.assertEquals(100, balance.getWeight(invoker1, invocation));
Assertions.assertEquals(30, balance.getWeight(invoker2, invocation));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("rawtypes")
class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest {
@Test
void testConsistentHashLoadBalanceInGenericCall() {
int runs = 10000;
Map<Invoker, AtomicLong> genericInvokeCounter = getGenericInvokeCounter(runs, ConsistentHashLoadBalance.NAME);
Map<Invoker, AtomicLong> invokeCounter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME);
Invoker genericHit = findHit(genericInvokeCounter);
Invoker hit = findHit(invokeCounter);
Assertions.assertEquals(hit, genericHit, "hit should equals to genericHit");
}
@Test
void testArgumentMatchAll() {
Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>();
LoadBalance lb = getLoadBalance(ConsistentHashLoadBalance.NAME);
for (Invoker invoker : invokers) {
counter.put(invoker, new AtomicLong(0));
}
URL url = invokers.get(0).getUrl();
for (int i = 0; i < 1000; i++) {
Invocation invocation = mock(Invocation.class);
String methodName = "method1";
given(invocation.getMethodName()).willReturn("$invoke");
String[] paraTypes = new String[] {String.class.getName(), String.class.getName(), String.class.getName()};
Object[] argsObject = new Object[] {"arg" + i, "arg2", "arg3"};
Object[] args = new Object[] {methodName, paraTypes, argsObject};
given(invocation.getArguments()).willReturn(args);
for (int j = 0; j < 5; j++) {
Invoker sinvoker = lb.select(invokers, url, invocation);
counter.get(sinvoker).incrementAndGet();
}
}
for (Invoker invoker : invokers) {
Assertions.assertTrue(counter.get(invoker).get() > 0);
}
}
private Invoker findHit(Map<Invoker, AtomicLong> invokerCounter) {
Invoker invoker = null;
for (Map.Entry<Invoker, AtomicLong> entry : invokerCounter.entrySet()) {
if (entry.getValue().longValue() > 0) {
invoker = entry.getKey();
break;
}
}
Assertions.assertNotNull(invoker, "invoker should be found");
return null;
}
@Test
void testConsistentHashLoadBalance() {
int runs = 10000;
long unHitInvokerCount = 0;
Map<Invoker, Long> hitInvokers = new HashMap<>();
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME);
for (Invoker minvoker : counter.keySet()) {
Long count = counter.get(minvoker).get();
if (count == 0) {
unHitInvokerCount++;
} else {
hitInvokers.put(minvoker, count);
}
}
Assertions.assertEquals(
counter.size() - 1, unHitInvokerCount, "the number of unHitInvoker should be counter.size() - 1");
Assertions.assertEquals(1, hitInvokers.size(), "the number of hitInvoker should be 1");
Assertions.assertEquals(
runs,
hitInvokers.values().iterator().next().intValue(),
"the number of hit count should be the number of runs");
}
// https://github.com/apache/dubbo/issues/5429
@Test
void testNormalWhenRouterEnabled() {
LoadBalance lb = getLoadBalance(ConsistentHashLoadBalance.NAME);
URL url = invokers.get(0).getUrl();
RouterChain<LoadBalanceBaseTest> routerChain = RouterChain.buildChain(LoadBalanceBaseTest.class, url);
Invoker<LoadBalanceBaseTest> result = lb.select(invokers, url, invocation);
for (int i = 0; i < 100; i++) {
routerChain.setInvokers(new BitList<>(invokers), () -> {});
List<Invoker<LoadBalanceBaseTest>> routeInvokers = routerChain
.getSingleChain(url, new BitList<>(invokers), invocation)
.route(url, new BitList<>(invokers), invocation);
Invoker<LoadBalanceBaseTest> finalInvoker = lb.select(routeInvokers, url, invocation);
Assertions.assertEquals(result, finalInvoker);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ShortestResponseLoadBalanceTest extends LoadBalanceBaseTest {
@Test
@Order(0)
public void testSelectByWeight() {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int loop = 10000;
ShortestResponseLoadBalance lb = new ShortestResponseLoadBalance();
lb.setApplicationModel(ApplicationModel.defaultModel());
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
}
// never select invoker5 because it's estimated response time is more than invoker1 and invoker2
Assertions.assertTrue(!selected.getUrl().getProtocol().equals("test5"), "select is not the shortest one");
}
// the sumInvoker1 : sumInvoker2 approximately equal to 1: 9
Assertions.assertEquals(sumInvoker1 + sumInvoker2, loop, "select failed!");
}
@Test
@Order(1)
public void testSelectByResponse() throws NoSuchFieldException, IllegalAccessException {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int sumInvoker5 = 0;
int loop = 10000;
// active -> 0
RpcStatus.endCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName(), 5000L, true);
ShortestResponseLoadBalance lb = new ShortestResponseLoadBalance();
lb.setApplicationModel(ApplicationModel.defaultModel());
// reset slideWindow
Field lastUpdateTimeField = ReflectUtils.forName(ShortestResponseLoadBalance.class.getName())
.getDeclaredField("lastUpdateTime");
lastUpdateTimeField.setAccessible(true);
lastUpdateTimeField.setLong(lb, System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(31));
lb.select(weightInvokersSR, null, weightTestInvocation);
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
}
if (selected.getUrl().getProtocol().equals("test5")) {
sumInvoker5++;
}
}
Map<Invoker<LoadBalanceBaseTest>, Integer> weightMap = weightInvokersSR.stream()
.collect(Collectors.toMap(
Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight"))));
Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum);
// max deviation = expectWeightValue * 2
int expectWeightValue = loop / totalWeight;
int maxDeviation = expectWeightValue * 2;
Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!");
Assertions.assertTrue(
Math.abs(sumInvoker2 / weightMap.get(weightInvoker2) - expectWeightValue) < maxDeviation,
"select failed!");
Assertions.assertTrue(
Math.abs(sumInvoker5 / weightMap.get(weightInvoker5) - expectWeightValue) < maxDeviation,
"select failed!");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled
class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest {
private void assertStrictWRRResult(int loop, Map<Invoker, InvokeResult> resultMap) {
int invokeCount = 0;
for (InvokeResult invokeResult : resultMap.values()) {
int count = (int) invokeResult.getCount().get();
// Because it's a strictly round robin, so the abs delta should be < 10 too
Assertions.assertTrue(
Math.abs(invokeResult.getExpected(loop) - count) < 10, "delta with expected count should < 10");
invokeCount += count;
}
Assertions.assertEquals(invokeCount, loop, "select failed!");
}
@Test
void testRoundRobinLoadBalanceSelect() {
int runs = 10000;
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RoundRobinLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < 1f, "abs diff should < 1");
}
}
@Test
void testSelectByWeight() {
final Map<Invoker, InvokeResult> totalMap = new HashMap<Invoker, InvokeResult>();
final AtomicBoolean shouldBegin = new AtomicBoolean(false);
final int runs = 10000;
List<Thread> threads = new ArrayList<Thread>();
int threadNum = 10;
for (int i = 0; i < threadNum; i++) {
threads.add(new Thread(() -> {
while (!shouldBegin.get()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
}
}
Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(runs, RoundRobinLoadBalance.NAME);
synchronized (totalMap) {
for (Entry<Invoker, InvokeResult> entry : resultMap.entrySet()) {
if (!totalMap.containsKey(entry.getKey())) {
totalMap.put(entry.getKey(), entry.getValue());
} else {
totalMap.get(entry.getKey())
.getCount()
.addAndGet(entry.getValue().getCount().get());
}
}
}
}));
}
for (Thread thread : threads) {
thread.start();
}
// let's rock it!
shouldBegin.set(true);
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
assertStrictWRRResult(runs * threadNum, totalMap);
}
@Test
void testNodeCacheShouldNotRecycle() {
int loop = 10000;
// temperately add a new invoker
weightInvokers.add(weightInvokerTmp);
try {
Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
// inner nodes cache judgement
RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME);
Assertions.assertEquals(
weightInvokers.size(),
lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
weightInvokers.remove(weightInvokerTmp);
resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
Assertions.assertNotEquals(
weightInvokers.size(),
lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
} finally {
// prevent other UT's failure
weightInvokers.remove(weightInvokerTmp);
}
}
@Test
void testNodeCacheShouldRecycle() {
{
Field recycleTimeField = null;
try {
// change recycle time to 1 ms
recycleTimeField = RoundRobinLoadBalance.class.getDeclaredField("RECYCLE_PERIOD");
recycleTimeField.setAccessible(true);
recycleTimeField.setInt(RoundRobinLoadBalance.class, 10);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) {
Assertions.assertTrue(true, "getField failed");
}
}
int loop = 10000;
// temperately add a new invoker
weightInvokers.add(weightInvokerTmp);
try {
Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
// inner nodes cache judgement
RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME);
Assertions.assertEquals(
weightInvokers.size(),
lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
weightInvokers.remove(weightInvokerTmp);
resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME);
assertStrictWRRResult(loop, resultMap);
Assertions.assertEquals(
weightInvokers.size(),
lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size());
} finally {
// prevent other UT's failure
weightInvokers.remove(weightInvokerTmp);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.rpc.Invoker;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class LeastActiveBalanceTest extends LoadBalanceBaseTest {
@Disabled
@Test
void testLeastActiveLoadBalance_select() {
int runs = 10000;
Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, LeastActiveLoadBalance.NAME);
for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) {
Long count = entry.getValue().get();
Assertions.assertTrue(
Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()),
"abs diff should < avg");
}
}
@Test
void testSelectByWeight() {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int loop = 10000;
LeastActiveLoadBalance lb = new LeastActiveLoadBalance();
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokers, null, weightTestInvocation);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
}
// never select invoker3 because it's active is more than invoker1 and invoker2
Assertions.assertTrue(
!selected.getUrl().getProtocol().equals("test3"), "select is not the least active one");
}
// the sumInvoker1 : sumInvoker2 approximately equal to 1: 9
Assertions.assertEquals(sumInvoker1 + sumInvoker2, loop, "select failed!");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AdaptiveMetrics;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest {
private ApplicationModel scopeModel;
private AdaptiveMetrics adaptiveMetrics;
@Test
@Order(0)
void testSelectByWeight() {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int sumInvoker3 = 0;
int loop = 10000;
ApplicationModel scopeModel = ApplicationModel.defaultModel();
AdaptiveLoadBalance lb = new AdaptiveLoadBalance(scopeModel);
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokers, null, weightTestInvocation);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
}
if (selected.getUrl().getProtocol().equals("test3")) {
sumInvoker3++;
}
}
// 1 : 9 : 6
Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!");
}
private String buildServiceKey(Invoker invoker) {
URL url = invoker.getUrl();
return url.getAddress() + ":" + invocation.getProtocolServiceKey();
}
private AdaptiveMetrics getAdaptiveMetricsInstance() {
if (adaptiveMetrics == null) {
adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class);
}
return adaptiveMetrics;
}
@Test
@Order(1)
void testSelectByAdaptive() {
int sumInvoker1 = 0;
int sumInvoker2 = 0;
int sumInvoker5 = 0;
int loop = 10000;
scopeModel = ApplicationModel.defaultModel();
AdaptiveLoadBalance lb = new AdaptiveLoadBalance(scopeModel);
lb.select(weightInvokersSR, null, weightTestInvocation);
for (int i = 0; i < loop; i++) {
Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation);
Map<String, String> metricsMap = new HashMap<>();
String idKey = buildServiceKey(selected);
if (selected.getUrl().getProtocol().equals("test1")) {
sumInvoker1++;
metricsMap.put("rt", "10");
metricsMap.put("load", "10");
metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 10));
getAdaptiveMetricsInstance().addConsumerSuccess(idKey);
}
if (selected.getUrl().getProtocol().equals("test2")) {
sumInvoker2++;
metricsMap.put("rt", "100");
metricsMap.put("load", "40");
metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 100));
getAdaptiveMetricsInstance().addConsumerSuccess(idKey);
}
if (selected.getUrl().getProtocol().equals("test5")) {
metricsMap.put("rt", "5000");
metricsMap.put("load", "400"); // 400%
metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 5000));
getAdaptiveMetricsInstance().addErrorReq(idKey);
sumInvoker5++;
}
getAdaptiveMetricsInstance().setProviderMetrics(idKey, metricsMap);
}
Map<Invoker<LoadBalanceBaseTest>, Integer> weightMap = weightInvokersSR.stream()
.collect(Collectors.toMap(
Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight"))));
Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum);
// max deviation = expectWeightValue * 2
int expectWeightValue = loop / totalWeight;
int maxDeviation = expectWeightValue * 2;
double beta = 0.5;
// this EMA is an approximate value
double ewma1 = beta * 50 + (1 - beta) * 10;
double ewma2 = beta * 50 + (1 - beta) * 100;
double ewma5 = beta * 50 + (1 - beta) * 5000;
AtomicInteger weight1 = new AtomicInteger();
AtomicInteger weight2 = new AtomicInteger();
AtomicInteger weight5 = new AtomicInteger();
weightMap.forEach((k, v) -> {
if (k.getUrl().getProtocol().equals("test1")) {
weight1.set(v);
} else if (k.getUrl().getProtocol().equals("test2")) {
weight2.set(v);
} else if (k.getUrl().getProtocol().equals("test5")) {
weight5.set(v);
}
});
Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!");
Assertions.assertTrue(
Math.abs(sumInvoker1 / (weightMap.get(weightInvoker1) * ewma1) - expectWeightValue) < maxDeviation,
"select failed!");
Assertions.assertTrue(
Math.abs(sumInvoker2 / (weightMap.get(weightInvoker2) * ewma2) - expectWeightValue) < maxDeviation,
"select failed!");
Assertions.assertTrue(
Math.abs(sumInvoker5 / (weightMap.get(weightInvoker5) * ewma5) - expectWeightValue) < maxDeviation,
"select failed!");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.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.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* RoundRobinLoadBalanceTest
*/
@SuppressWarnings({"unchecked", "rawtypes"})
class LoadBalanceBaseTest {
Invocation invocation;
Invocation genericInvocation;
List<Invoker<LoadBalanceBaseTest>> invokers = new ArrayList<Invoker<LoadBalanceBaseTest>>();
Invoker<LoadBalanceBaseTest> invoker1;
Invoker<LoadBalanceBaseTest> invoker2;
Invoker<LoadBalanceBaseTest> invoker3;
Invoker<LoadBalanceBaseTest> invoker4;
Invoker<LoadBalanceBaseTest> invoker5;
RpcStatus weightTestRpcStatus1;
RpcStatus weightTestRpcStatus2;
RpcStatus weightTestRpcStatus3;
RpcStatus weightTestRpcStatus5;
RpcInvocation weightTestInvocation;
/**
* @throws java.lang.Exception
*/
@BeforeAll
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
invocation = mock(Invocation.class);
given(invocation.getMethodName()).willReturn("method1");
given(invocation.getArguments()).willReturn(new Object[] {"arg1", "arg2", "arg3"});
genericInvocation = mock(Invocation.class);
String methodName = "method1";
given(genericInvocation.getMethodName()).willReturn("$invoke");
String[] paraTypes = new String[] {String.class.getName(), String.class.getName(), String.class.getName()};
Object[] argsObject = new Object[] {"arg1", "arg2", "arg3"};
Object[] args = new Object[] {methodName, paraTypes, argsObject};
given(genericInvocation.getArguments()).willReturn(args);
invoker1 = mock(Invoker.class);
invoker2 = mock(Invoker.class);
invoker3 = mock(Invoker.class);
invoker4 = mock(Invoker.class);
invoker5 = mock(Invoker.class);
URL url1 = URL.valueOf("test://127.0.0.1:1/DemoService");
URL url2 = URL.valueOf("test://127.0.0.1:2/DemoService");
URL url3 = URL.valueOf("test://127.0.0.1:3/DemoService");
URL url4 = URL.valueOf("test://127.0.0.1:4/DemoService");
URL url5 = URL.valueOf("test://127.0.0.1:5/DemoService");
given(invoker1.isAvailable()).willReturn(true);
given(invoker1.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(invoker1.getUrl()).willReturn(url1);
given(invoker2.isAvailable()).willReturn(true);
given(invoker2.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(invoker2.getUrl()).willReturn(url2);
given(invoker3.isAvailable()).willReturn(true);
given(invoker3.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(invoker3.getUrl()).willReturn(url3);
given(invoker4.isAvailable()).willReturn(true);
given(invoker4.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(invoker4.getUrl()).willReturn(url4);
given(invoker5.isAvailable()).willReturn(true);
given(invoker5.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(invoker5.getUrl()).willReturn(url5);
invokers.add(invoker1);
invokers.add(invoker2);
invokers.add(invoker3);
invokers.add(invoker4);
invokers.add(invoker5);
}
public Map<Invoker, AtomicLong> getInvokeCounter(int runs, String loadbalanceName) {
Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>();
LoadBalance lb = getLoadBalance(loadbalanceName);
for (Invoker invoker : invokers) {
counter.put(invoker, new AtomicLong(0));
}
URL url = invokers.get(0).getUrl();
for (int i = 0; i < runs; i++) {
Invoker sinvoker = lb.select(invokers, url, invocation);
counter.get(sinvoker).incrementAndGet();
}
return counter;
}
public Map<Invoker, AtomicLong> getGenericInvokeCounter(int runs, String loadbalanceName) {
Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>();
LoadBalance lb = getLoadBalance(loadbalanceName);
for (Invoker invoker : invokers) {
counter.put(invoker, new AtomicLong(0));
}
URL url = invokers.get(0).getUrl();
for (int i = 0; i < runs; i++) {
Invoker sinvoker = lb.select(invokers, url, genericInvocation);
counter.get(sinvoker).incrementAndGet();
}
return counter;
}
protected AbstractLoadBalance getLoadBalance(String loadbalanceName) {
return (AbstractLoadBalance)
ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName);
}
@Test
void testLoadBalanceWarmup() {
Assertions.assertEquals(1, calculateDefaultWarmupWeight(0));
Assertions.assertEquals(1, calculateDefaultWarmupWeight(13));
Assertions.assertEquals(1, calculateDefaultWarmupWeight(6 * 1000));
Assertions.assertEquals(2, calculateDefaultWarmupWeight(12 * 1000));
Assertions.assertEquals(10, calculateDefaultWarmupWeight(60 * 1000));
Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000));
Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 23));
Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 5999));
Assertions.assertEquals(51, calculateDefaultWarmupWeight(5 * 60 * 1000 + 6000));
Assertions.assertEquals(90, calculateDefaultWarmupWeight(9 * 60 * 1000));
Assertions.assertEquals(98, calculateDefaultWarmupWeight(10 * 60 * 1000 - 12 * 1000));
Assertions.assertEquals(99, calculateDefaultWarmupWeight(10 * 60 * 1000 - 6 * 1000));
Assertions.assertEquals(100, calculateDefaultWarmupWeight(10 * 60 * 1000));
Assertions.assertEquals(100, calculateDefaultWarmupWeight(20 * 60 * 1000));
}
/**
* handle default data
*
* @return
*/
private static int calculateDefaultWarmupWeight(int uptime) {
return AbstractLoadBalance.calculateWarmupWeight(uptime, DEFAULT_WARMUP, DEFAULT_WEIGHT);
}
/*------------------------------------test invokers for weight---------------------------------------*/
protected static class InvokeResult {
private AtomicLong count = new AtomicLong();
private int weight = 0;
private int totalWeight = 0;
public InvokeResult(int weight) {
this.weight = weight;
}
public AtomicLong getCount() {
return count;
}
public int getWeight() {
return weight;
}
public int getTotalWeight() {
return totalWeight;
}
public void setTotalWeight(int totalWeight) {
this.totalWeight = totalWeight;
}
public int getExpected(int runCount) {
return getWeight() * runCount / getTotalWeight();
}
public float getDeltaPercentage(int runCount) {
int expected = getExpected(runCount);
return Math.abs((expected - getCount().get()) * 100.0f / expected);
}
@Override
public String toString() {
return JsonUtils.toJson(this);
}
}
protected List<Invoker<LoadBalanceBaseTest>> weightInvokers = new ArrayList<Invoker<LoadBalanceBaseTest>>();
protected List<Invoker<LoadBalanceBaseTest>> weightInvokersSR = new ArrayList<Invoker<LoadBalanceBaseTest>>();
protected Invoker<LoadBalanceBaseTest> weightInvoker1;
protected Invoker<LoadBalanceBaseTest> weightInvoker2;
protected Invoker<LoadBalanceBaseTest> weightInvoker3;
protected Invoker<LoadBalanceBaseTest> weightInvokerTmp;
protected Invoker<LoadBalanceBaseTest> weightInvoker5;
@BeforeEach
public void before() throws Exception {
weightInvoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightInvoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightInvoker3 = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightInvokerTmp = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightInvoker5 = mock(Invoker.class, Mockito.withSettings().stubOnly());
weightTestInvocation = new RpcInvocation();
weightTestInvocation.setMethodName("test");
URL url1 = URL.valueOf("test1://127.0.0.1:11/DemoService?weight=1&active=0");
URL url2 = URL.valueOf("test2://127.0.0.1:12/DemoService?weight=9&active=0");
URL url3 = URL.valueOf("test3://127.0.0.1:13/DemoService?weight=6&active=1");
URL urlTmp = URL.valueOf("test4://127.0.0.1:9999/DemoService?weight=11&active=0");
URL url5 = URL.valueOf("test5://127.0.0.1:15/DemoService?weight=15&active=0");
given(weightInvoker1.isAvailable()).willReturn(true);
given(weightInvoker1.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(weightInvoker1.getUrl()).willReturn(url1);
given(weightInvoker2.isAvailable()).willReturn(true);
given(weightInvoker2.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(weightInvoker2.getUrl()).willReturn(url2);
given(weightInvoker3.isAvailable()).willReturn(true);
given(weightInvoker3.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(weightInvoker3.getUrl()).willReturn(url3);
given(weightInvokerTmp.isAvailable()).willReturn(true);
given(weightInvokerTmp.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(weightInvokerTmp.getUrl()).willReturn(urlTmp);
given(weightInvoker5.isAvailable()).willReturn(true);
given(weightInvoker5.getInterface()).willReturn(LoadBalanceBaseTest.class);
given(weightInvoker5.getUrl()).willReturn(url5);
weightInvokers.add(weightInvoker1);
weightInvokers.add(weightInvoker2);
weightInvokers.add(weightInvoker3);
weightInvokersSR.add(weightInvoker1);
weightInvokersSR.add(weightInvoker2);
weightInvokersSR.add(weightInvoker5);
weightTestRpcStatus1 = RpcStatus.getStatus(weightInvoker1.getUrl(), weightTestInvocation.getMethodName());
weightTestRpcStatus2 = RpcStatus.getStatus(weightInvoker2.getUrl(), weightTestInvocation.getMethodName());
weightTestRpcStatus3 = RpcStatus.getStatus(weightInvoker3.getUrl(), weightTestInvocation.getMethodName());
weightTestRpcStatus5 = RpcStatus.getStatus(weightInvoker5.getUrl(), weightTestInvocation.getMethodName());
// weightTestRpcStatus3 active is 1
RpcStatus.beginCount(weightInvoker3.getUrl(), weightTestInvocation.getMethodName());
// weightTestRpcStatus5 shortest response time of success calls is bigger than 0
// weightTestRpcStatus5 active is 1
RpcStatus.beginCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName());
RpcStatus.endCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName(), 5000L, true);
RpcStatus.beginCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName());
}
protected Map<Invoker, InvokeResult> getWeightedInvokeResult(int runs, String loadbalanceName) {
Map<Invoker, InvokeResult> counter = new ConcurrentHashMap<Invoker, InvokeResult>();
AbstractLoadBalance lb = getLoadBalance(loadbalanceName);
int totalWeight = 0;
for (int i = 0; i < weightInvokers.size(); i++) {
InvokeResult invokeResult = new InvokeResult(lb.getWeight(weightInvokers.get(i), weightTestInvocation));
counter.put(weightInvokers.get(i), invokeResult);
totalWeight += invokeResult.getWeight();
}
for (InvokeResult invokeResult : counter.values()) {
invokeResult.setTotalWeight(totalWeight);
}
URL url = weightInvokers.get(0).getUrl();
for (int i = 0; i < runs; i++) {
Invoker sinvoker = lb.select(weightInvokers, url, weightTestInvocation);
counter.get(sinvoker).getCount().incrementAndGet();
}
return counter;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.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.rpc.cluster.router;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class RouterSnapshotFilterTest {
@BeforeAll
static void setUp() {
RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false);
}
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
RouterSnapshotSwitcher routerSnapshotSwitcher =
frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
RouterSnapshotFilter routerSnapshotFilter = new RouterSnapshotFilter(frameworkModel);
Invoker invoker = Mockito.mock(Invoker.class);
Invocation invocation = Mockito.mock(Invocation.class);
ServiceModel serviceModel = Mockito.mock(ServiceModel.class);
Mockito.when(serviceModel.getServiceKey()).thenReturn("TestKey");
Mockito.when(invocation.getServiceModel()).thenReturn(serviceModel);
routerSnapshotFilter.invoke(invoker, invocation);
Mockito.verify(invoker, Mockito.times(1)).invoke(invocation);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotSwitcher.addEnabledService("Test");
routerSnapshotFilter.invoke(invoker, invocation);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotSwitcher.removeEnabledService("Test");
routerSnapshotFilter.invoke(invoker, invocation);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotSwitcher.addEnabledService("TestKey");
routerSnapshotFilter.invoke(invoker, invocation);
Assertions.assertTrue(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotFilter.onResponse(null, null, null);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotSwitcher.addEnabledService("TestKey");
routerSnapshotFilter.invoke(invoker, invocation);
Assertions.assertTrue(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotFilter.onError(null, null, null);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotSwitcher.removeEnabledService("TestKey");
routerSnapshotFilter.invoke(invoker, invocation);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
routerSnapshotFilter.onError(null, null, null);
Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.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.rpc.cluster.router;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
public class MockInvoker<T> implements Invoker<T> {
private boolean available = false;
private URL url;
public MockInvoker() {}
public MockInvoker(URL url) {
super();
this.url = url;
}
public MockInvoker(URL url, boolean available) {
super();
this.url = url;
this.available = available;
}
public MockInvoker(boolean available) {
this.available = available;
}
@Override
public Class<T> getInterface() {
return null;
}
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return available;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return null;
}
@Override
public void destroy() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.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.rpc.cluster.router.state;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.provider.ValueSource;
class BitListTest {
@Test
void test() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals(bitList.getOriginList(), list);
Assertions.assertEquals(3, bitList.size());
Assertions.assertEquals("A", bitList.get(0));
Assertions.assertEquals("B", bitList.get(1));
Assertions.assertEquals("C", bitList.get(2));
Assertions.assertTrue(bitList.contains("A"));
Assertions.assertTrue(bitList.contains("B"));
Assertions.assertTrue(bitList.contains("C"));
for (String str : bitList) {
Assertions.assertTrue(list.contains(str));
}
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(1, bitList.indexOf("B"));
Assertions.assertEquals(2, bitList.indexOf("C"));
Object[] objects = bitList.toArray();
for (Object obj : objects) {
Assertions.assertTrue(list.contains(obj));
}
Object[] newObjects = new Object[1];
Object[] copiedList = bitList.toArray(newObjects);
Assertions.assertEquals(3, copiedList.length);
Assertions.assertArrayEquals(copiedList, list.toArray());
newObjects = new Object[10];
copiedList = bitList.toArray(newObjects);
Assertions.assertEquals(10, copiedList.length);
Assertions.assertEquals("A", copiedList[0]);
Assertions.assertEquals("B", copiedList[1]);
Assertions.assertEquals("C", copiedList[2]);
bitList.remove(0);
Assertions.assertEquals("B", bitList.get(0));
bitList.addIndex(0);
Assertions.assertEquals("A", bitList.get(0));
bitList.removeAll(list);
Assertions.assertEquals(0, bitList.size());
bitList.clear();
}
@Test
void testIntersect() {
List<String> aList = Arrays.asList("A", "B", "C");
List<String> bList = Arrays.asList("A", "B");
List<String> totalList = Arrays.asList("A", "B", "C");
BitList<String> aBitList = new BitList<>(aList);
BitList<String> bBitList = new BitList<>(bList);
BitList<String> intersectBitList = aBitList.and(bBitList);
Assertions.assertEquals(2, intersectBitList.size());
Assertions.assertEquals(totalList.get(0), intersectBitList.get(0));
Assertions.assertEquals(totalList.get(1), intersectBitList.get(1));
aBitList.add("D");
intersectBitList = aBitList.and(bBitList);
Assertions.assertEquals(3, intersectBitList.size());
Assertions.assertEquals(totalList.get(0), intersectBitList.get(0));
Assertions.assertEquals(totalList.get(1), intersectBitList.get(1));
Assertions.assertEquals("D", intersectBitList.get(2));
}
@Test
void testIsEmpty() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
bitList.add("D");
bitList.removeAll(list);
Assertions.assertEquals(1, bitList.size());
bitList.remove("D");
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testAdd() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
bitList.remove("A");
Assertions.assertEquals(2, bitList.size());
bitList.addAll(Collections.singletonList("A"));
Assertions.assertEquals(3, bitList.size());
bitList.addAll(Collections.singletonList("D"));
Assertions.assertEquals(4, bitList.size());
Assertions.assertEquals("D", bitList.get(3));
Assertions.assertTrue(bitList.hasMoreElementInTailList());
Assertions.assertEquals(Collections.singletonList("D"), bitList.getTailList());
bitList.clear();
bitList.addAll(Collections.singletonList("A"));
Assertions.assertEquals(1, bitList.size());
Assertions.assertEquals("A", bitList.get(0));
}
@Test
void testAddAll() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList1 = new BitList<>(list);
BitList<String> bitList2 = new BitList<>(list);
bitList1.removeAll(list);
Assertions.assertEquals(0, bitList1.size());
bitList1.addAll(bitList2);
Assertions.assertEquals(3, bitList1.size());
Assertions.assertFalse(bitList1.hasMoreElementInTailList());
bitList1.addAll(bitList2);
Assertions.assertEquals(3, bitList1.size());
}
@Test
void testGet() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals("A", bitList.get(0));
Assertions.assertEquals("B", bitList.get(1));
Assertions.assertEquals("C", bitList.get(2));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(-1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(3));
bitList.add("D");
Assertions.assertEquals("D", bitList.get(3));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(-1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(4));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(5));
}
@Test
void testRemove() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertTrue(bitList.remove("A"));
Assertions.assertFalse(bitList.remove("A"));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("B")));
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("B")));
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("D")));
bitList.add("D");
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("D")));
Assertions.assertFalse(bitList.hasMoreElementInTailList());
bitList.add("A");
bitList.add("E");
bitList.add("F");
Assertions.assertEquals(4, bitList.size());
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("D")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("A")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("C")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("E")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("F")));
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testRemoveIndex() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(3));
Assertions.assertNotNull(bitList.remove(1));
Assertions.assertNotNull(bitList.remove(0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(1));
bitList.add("D");
Assertions.assertNotNull(bitList.remove(1));
bitList.add("A");
bitList.add("E");
bitList.add("F");
// A C E F
Assertions.assertEquals(4, bitList.size());
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(4));
Assertions.assertEquals("F", bitList.remove(3));
Assertions.assertEquals("E", bitList.remove(2));
Assertions.assertEquals("C", bitList.remove(1));
Assertions.assertEquals("A", bitList.remove(0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(0));
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testRetain() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
List<String> list1 = Arrays.asList("B", "C");
Assertions.assertTrue(bitList.retainAll(list1));
Assertions.assertTrue(bitList.containsAll(list1));
Assertions.assertFalse(bitList.containsAll(list));
Assertions.assertFalse(bitList.contains("A"));
bitList = new BitList<>(list);
bitList.add("D");
bitList.add("E");
List<String> list2 = Arrays.asList("B", "C", "D");
Assertions.assertTrue(bitList.retainAll(list2));
Assertions.assertTrue(bitList.containsAll(list2));
Assertions.assertFalse(bitList.containsAll(list));
Assertions.assertFalse(bitList.contains("A"));
Assertions.assertFalse(bitList.contains("E"));
}
@Test
void testIndex() {
List<String> list = Arrays.asList("A", "B", "A");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(2, bitList.lastIndexOf("A"));
Assertions.assertEquals(-1, bitList.indexOf("D"));
Assertions.assertEquals(-1, bitList.lastIndexOf("D"));
bitList.add("D");
bitList.add("E");
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(2, bitList.lastIndexOf("A"));
Assertions.assertEquals(3, bitList.indexOf("D"));
Assertions.assertEquals(3, bitList.lastIndexOf("D"));
Assertions.assertEquals(-1, bitList.indexOf("F"));
}
@Test
void testSubList() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
BitList<String> subList1 = bitList.subList(0, 5);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D", "E"), subList1);
BitList<String> subList2 = bitList.subList(1, 5);
Assertions.assertEquals(Arrays.asList("B", "C", "D", "E"), subList2);
BitList<String> subList3 = bitList.subList(0, 4);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D"), subList3);
BitList<String> subList4 = bitList.subList(1, 4);
Assertions.assertEquals(Arrays.asList("B", "C", "D"), subList4);
BitList<String> subList5 = bitList.subList(2, 3);
Assertions.assertEquals(Collections.singletonList("C"), subList5);
Assertions.assertFalse(subList5.hasMoreElementInTailList());
BitList<String> subList6 = bitList.subList(0, 9);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"), subList6);
Assertions.assertEquals(Arrays.asList("F", "G", "H", "I"), subList6.getTailList());
BitList<String> subList7 = bitList.subList(1, 8);
Assertions.assertEquals(Arrays.asList("B", "C", "D", "E", "F", "G", "H"), subList7);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList7.getTailList());
BitList<String> subList8 = bitList.subList(4, 8);
Assertions.assertEquals(Arrays.asList("E", "F", "G", "H"), subList8);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList8.getTailList());
BitList<String> subList9 = bitList.subList(5, 8);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList9);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList9.getTailList());
BitList<String> subList10 = bitList.subList(6, 8);
Assertions.assertEquals(Arrays.asList("G", "H"), subList10);
Assertions.assertEquals(Arrays.asList("G", "H"), subList10.getTailList());
BitList<String> subList11 = bitList.subList(6, 7);
Assertions.assertEquals(Collections.singletonList("G"), subList11);
Assertions.assertEquals(Collections.singletonList("G"), subList11.getTailList());
}
@Test
void testListIterator1() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = list.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
@ValueSource(
ints = {
2,
})
void testListIterator2() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator3() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator4() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(8);
ListIterator<String> expectedIterator = expectedResult.listIterator(8);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator5() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator6() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator7() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator8() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testClone1() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
BitList<String> clone1 = bitList.clone();
Assertions.assertNotSame(bitList, clone1);
Assertions.assertEquals(bitList, clone1);
HashSet<Object> set = new HashSet<>();
set.add(bitList);
set.add(clone1);
Assertions.assertEquals(1, set.size());
set.add(new LinkedList<>());
Assertions.assertEquals(2, set.size());
set.add(new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E")));
Assertions.assertEquals(2, set.size());
}
@Test
void testClone2() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G"));
BitList<String> clone1 = bitList.clone();
Assertions.assertNotSame(bitList, clone1);
Assertions.assertEquals(bitList, clone1);
HashSet<Object> set = new HashSet<>();
set.add(bitList);
set.add(clone1);
Assertions.assertEquals(1, set.size());
set.add(new LinkedList<>());
Assertions.assertEquals(2, set.size());
set.add(new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G")));
Assertions.assertEquals(2, set.size());
}
@Test
void testConcurrent() throws InterruptedException {
for (int i = 0; i < 100000; i++) {
BitList<String> bitList = new BitList<>(Collections.singletonList("test"));
bitList.remove("test");
CountDownLatch countDownLatch = new CountDownLatch(1);
CountDownLatch countDownLatch2 = new CountDownLatch(2);
Thread thread1 = new Thread(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
bitList.add("test");
countDownLatch2.countDown();
});
AtomicReference<BitList<String>> ref = new AtomicReference<>();
Thread thread2 = new Thread(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
ref.set(bitList.clone());
countDownLatch2.countDown();
});
thread1.start();
thread2.start();
countDownLatch.countDown();
countDownLatch2.await();
Assertions.assertDoesNotThrow(() -> ref.get().iterator().hasNext());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.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.rpc.cluster.router.file;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.script.ScriptEngineManager;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class FileRouterEngineTest {
private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null;
List<Invoker<FileRouterEngineTest>> invokers = new ArrayList<Invoker<FileRouterEngineTest>>();
Invoker<FileRouterEngineTest> invoker1 = mock(Invoker.class);
Invoker<FileRouterEngineTest> invoker2 = mock(Invoker.class);
Invocation invocation;
StaticDirectory<FileRouterEngineTest> dic;
Result result = new AppResponse();
private StateRouterFactory routerFactory =
ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getAdaptiveExtension();
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false");
}
@BeforeEach
public void setUp() throws Exception {
invokers.add(invoker1);
invokers.add(invoker2);
}
@AfterEach
public void teardown() throws Exception {
System.clearProperty(ENABLE_CONNECTIVITY_VALIDATION);
RpcContext.removeContext();
}
@Test
void testRouteNotAvailable() {
if (isScriptUnsupported) return;
URL url = initUrl("notAvailablerule.javascript");
initInvocation("method1");
initInvokers(url, true, false);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker2, invoker);
}
}
@Test
void testRouteAvailable() {
if (isScriptUnsupported) return;
URL url = initUrl("availablerule.javascript");
initInvocation("method1");
initInvokers(url);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker1, invoker);
}
}
@Test
void testRouteByMethodName() {
if (isScriptUnsupported) return;
URL url = initUrl("methodrule.javascript");
{
initInvocation("method1");
initInvokers(url, true, true);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker1, invoker);
}
}
{
initInvocation("method2");
initInvokers(url, true, true);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker2, invoker);
}
}
}
private URL initUrl(String filename) {
filename = getClass()
.getClassLoader()
.getResource(getClass().getPackage().getName().replace('.', '/') + "/" + filename)
.toString();
URL url = URL.valueOf(filename);
url = url.addParameter(RUNTIME_KEY, true);
return url;
}
private void initInvocation(String methodName) {
invocation = new RpcInvocation();
((RpcInvocation) invocation).setMethodName(methodName);
}
private void initInvokers(URL url) {
initInvokers(url, true, false);
}
private void initInvokers(URL url, boolean invoker1Status, boolean invoker2Status) {
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.isAvailable()).willReturn(invoker1Status);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FileRouterEngineTest.class);
given(invoker2.invoke(invocation)).willReturn(result);
given(invoker2.isAvailable()).willReturn(invoker2Status);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FileRouterEngineTest.class);
}
private void initDic(URL url) {
// FIXME: this exposes the design flaw in RouterChain
URL dicInitUrl = URL.valueOf(
"consumer://localhost:20880/org.apache.dubbo.rpc.cluster.router.file.FileRouterEngineTest?application=FileRouterEngineTest");
dic = new StaticDirectory<>(dicInitUrl, invokers);
dic.buildRouterChain();
dic.getRouterChain()
.getCurrentChain()
.setHeadStateRouter(routerFactory.getRouter(FileRouterEngineTest.class, url));
}
static class MockClusterInvoker<T> extends AbstractClusterInvoker<T> {
private Invoker<T> selectedInvoker;
public MockClusterInvoker(Directory<T> directory) {
super(directory);
}
public MockClusterInvoker(Directory<T> directory, URL url) {
super(directory, url);
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
selectedInvoker = invoker;
return null;
}
public Invoker<T> getSelectedInvoker() {
return selectedInvoker;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.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.rpc.cluster.router.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
class MockInvokersSelectorTest {
@Test
void test() {
MockInvokersSelector selector = new MockInvokersSelector(URL.valueOf(""));
// Data preparation
Invoker<DemoService> invoker1 = Mockito.mock(Invoker.class);
Invoker<DemoService> invoker2 = Mockito.mock(Invoker.class);
Invoker<DemoService> invoker3 = Mockito.mock(Invoker.class);
Mockito.when(invoker1.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker2.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker3.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1/test"));
BitList<Invoker<DemoService>> providers = new BitList<>(Arrays.asList(invoker1, invoker2, invoker3));
RpcInvocation rpcInvocation = Mockito.mock(RpcInvocation.class);
URL consumerURL = URL.valueOf("test://127.0.0.1");
selector.notify(providers);
// rpcInvocation does not have an attached "invocation.need.mock" parameter, so normal invokers will be filtered
// out
List<Invoker<DemoService>> invokers =
selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>());
Assertions.assertEquals(invokers.size(), 1);
Assertions.assertTrue(invokers.contains(invoker3));
// rpcInvocation have an attached "invocation.need.mock" parameter, so it will filter out the invoker whose
// protocol is mock
Mockito.when(rpcInvocation.getObjectAttachmentWithoutConvert(INVOCATION_NEED_MOCK))
.thenReturn("true");
invokers = selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>());
Assertions.assertEquals(invokers.size(), 2);
Assertions.assertTrue(invokers.contains(invoker1));
Assertions.assertTrue(invokers.contains(invoker2));
}
class DemoService {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/affinity/AffinityRouteTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/affinity/AffinityRouteTest.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.rpc.cluster.router.affinity;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.affinity.config.AffinityServiceStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AffinityRouteTest {
private static final Logger logger = LoggerFactory.getLogger(AffinityRouteTest.class);
private static BitList<Invoker<String>> invokers;
private static List<String> providerUrls;
@BeforeAll
public static void setUp() {
providerUrls = Arrays.asList(
"dubbo://127.0.0.1/com.foo.BarService",
"dubbo://127.0.0.1/com.foo.BarService",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService",
"dubbo://dubbo.apache.org/com.foo.BarService",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal");
List<Invoker<String>> invokerList = providerUrls.stream()
.map(url -> new MockInvoker<String>(URL.valueOf(url)))
.collect(Collectors.toList());
invokers = new BitList<>(invokerList);
}
public List<String> filtrate(List<String> invokers, String key) {
return invokers.stream().filter(invoker -> invoker.contains(key)).collect(Collectors.toList());
}
@Test
void testMetAffinityRoute() {
String config = "configVersion: v3.1\n"
+ "scope: service\n"
+ "key: service.apache.com\n"
+ "enabled: true\n"
+ "runtime: true\n"
+ "affinityAware:\n"
+ " key: region\n"
+ " ratio: 20\n";
AffinityServiceStateRouter<String> affinityRoute = new AffinityServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
affinityRoute.process(new ConfigChangedEvent("com.foo.BarService", "", config, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> res = affinityRoute.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
List<String> filtered = filtrate(new ArrayList<String>(providerUrls), "region=beijing");
assertEquals(filtered.size(), res.size());
logger.info("The affinity routing condition is met and the result is routed");
}
@Test
void testUnMetAffinityRoute() {
String config = "configVersion: v3.1\n"
+ "scope: service\n"
+ "key: service.apache.com\n"
+ "enabled: true\n"
+ "runtime: true\n"
+ "affinityAware:\n"
+ " key: region\n"
+ " ratio: 80\n";
AffinityServiceStateRouter<String> affinityRoute = new AffinityServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
affinityRoute.process(new ConfigChangedEvent("com.foo.BarService", "", config, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> res = affinityRoute.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
List<String> filtered = filtrate(new ArrayList<String>(providerUrls), "region=beijing");
assertEquals(invokers.size(), res.size());
logger.info("The affinity routing condition was not met and the result was not routed");
}
@Test
void testRatioEqualsAffinityRoute() {
String config = "configVersion: v3.1\n"
+ "scope: service\n"
+ "key: service.apache.com\n"
+ "enabled: true\n"
+ "runtime: true\n"
+ "affinityAware:\n"
+ " key: region\n"
+ " ratio: 40\n";
AffinityServiceStateRouter<String> affinityRoute = new AffinityServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
affinityRoute.process(new ConfigChangedEvent("com.foo.BarService", "", config, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> res = affinityRoute.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
List<String> filtered = filtrate(new ArrayList<String>(providerUrls), "region=beijing");
assertEquals(filtered.size(), res.size());
logger.info("The affinity routing condition is met and the result is routed");
}
@Test
void testRatioNotEqualsAffinityRoute() {
String config = "configVersion: v3.1\n"
+ "scope: service\n"
+ "key: service.apache.com\n"
+ "enabled: true\n"
+ "runtime: true\n"
+ "affinityAware:\n"
+ " key: region\n"
+ " ratio: 40.1\n";
AffinityServiceStateRouter<String> affinityRoute = new AffinityServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
affinityRoute.process(new ConfigChangedEvent("com.foo.BarService", "", config, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> res = affinityRoute.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
List<String> filtered = filtrate(new ArrayList<String>(providerUrls), "region=beijing");
assertEquals(invokers.size(), res.size());
logger.info("The affinity routing condition was not met and the result was not routed");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.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.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
class ScriptStateRouterTest {
private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript");
@BeforeAll
public static void setUpBeforeClass() throws Exception {}
@BeforeEach
public void setUp() throws Exception {}
private URL getRouteUrl(String rule) {
return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule);
}
@Test
void testRouteReturnAll() {
StateRouter router = new ScriptStateRouterFactory()
.getRouter(String.class, getRouteUrl("function route(op1,op2){return op1} route(invokers)"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoutePickInvokers() {
String rule = "var result = new java.util.ArrayList(invokers.size());" + "for (i=0;i<invokers.size(); i++){ "
+ "if (invokers.get(i).isAvailable()) {"
+ "result.add(invokers.get(i)) ;"
+ "}"
+ "} ; "
+ "return result;";
String script = "function route(invokers,invocation,context){" + rule + "} route(invokers,invocation,context)";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(false);
Invoker<String> invoker2 = new MockInvoker<String>(true);
Invoker<String> invoker3 = new MockInvoker<String>(true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRouteHostFilter() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "function route(invokers, invocation, context){ "
+ " var result = new java.util.ArrayList(invokers.size()); "
+ " var targetHost = new java.util.ArrayList(); "
+ " targetHost.add(\"10.134.108.2\"); "
+ " for (var i = 0; i < invokers.length; i++) { "
+ " if(targetHost.contains(invokers[i].getUrl().getHost())){ "
+ " result.add(invokers[i]); "
+ " } "
+ " } "
+ " return result; "
+ "} "
+ "route(invokers, invocation, context) ";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(1, routeResult.size());
Assertions.assertEquals(invoker2, routeResult.get(0));
}
@Test
void testRoute_throwException() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "/";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(3, routeResult.size());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.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.rpc.cluster.router.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
public class AppScriptStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private static final String RULE_SUFFIX = ".script-router";
private static GovernanceRuleRepository ruleRepository;
private URL url = URL.valueOf("dubbo://1.1.1.1/com.foo.BarService");
private String rawRule = "---\n" + "configVersion: v3.0\n"
+ "key: demo-provider\n"
+ "type: javascript\n"
+ "script: |\n"
+ " (function route(invokers,invocation,context) {\n"
+ " var result = new java.util.ArrayList(invokers.size());\n"
+ " for (i = 0; i < invokers.size(); i ++) {\n"
+ " if (\"10.20.3.3\".equals(invokers.get(i).getUrl().getHost())) {\n"
+ " result.add(invokers.get(i));\n"
+ " }\n"
+ " }\n"
+ " return result;\n"
+ " } (invokers, invocation, context)); // 表示立即执行方法\n"
+ "...";
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ruleRepository = Mockito.mock(GovernanceRuleRepository.class);
}
@Test
void testConfigScriptRoute() {
AppScriptStateRouter<String> router = new AppScriptStateRouter<>(url);
router = Mockito.spy(router);
Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository);
Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP))
.thenReturn(rawRule);
// Mockito.when(ruleRepository.addListener()).thenReturn();
BitList<Invoker<String>> invokers = getInvokers();
router.notify(invokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
List<Invoker<String>> result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(1, result.size());
}
private BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.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.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
class ConditionStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService");
@BeforeAll
public static void setUpBeforeClass() throws Exception {}
@BeforeEach
public void setUp() throws Exception {}
private URL getRouteUrl(String rule) {
return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule);
}
@Test
void testRoute_matchWhen() {
Invocation invocation = new RpcInvocation();
StateRouter router =
new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => host = 1.2.3.4"));
boolean matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
}
@Test
void testRoute_matchFilter() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
System.err.println("The localhost address: " + invoker2.getUrl().getAddress());
System.err.println(invoker3.getUrl().getAddress());
StateRouter router1 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router2 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router3 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router4 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router5 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router6 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " serialization = fastjson")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router1.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers2 = router2.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers3 = router3.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers4 = router4.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers5 = router5.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers6 = router6.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers1.size());
Assertions.assertEquals(0, filteredInvokers2.size());
Assertions.assertEquals(0, filteredInvokers3.size());
Assertions.assertEquals(1, filteredInvokers4.size());
Assertions.assertEquals(2, filteredInvokers5.size());
Assertions.assertEquals(1, filteredInvokers6.size());
}
@Test
void testRoute_methodRoute() {
Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class<?>[0], new Object[0]);
// More than one methods, mismatch
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo => host = 1.2.3.4"));
boolean matchWhen = ((ConditionStateRouter) router)
.matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Exactly one method, match
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Method routing and Other condition routing can work together
StateRouter router2 = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router2)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertFalse(matchWhen);
StateRouter router3 = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router3)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Test filter condition
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
StateRouter router4 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router4.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers1.size());
StateRouter router5 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers2 = router5.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers2.size());
// Request a non-exists method
}
@Test
void testRoute_ReturnFalse() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => false"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_ReturnEmpty() {
StateRouter router =
new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => "));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_ReturnAll() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoute_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_Empty_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl(" => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_False_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("true => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_Placeholder() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_NoForce() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoute_Force() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_Arguments() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
String p = "a";
invocation.setArguments(new Object[] {null});
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
invocation.setArguments(new Object[] {p});
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
int integer = 1;
invocation.setArguments(new Object[] {integer});
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_Attachments() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[foo] = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 =
new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
invocation.setAttachment("foo", "a");
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[foo] = a " + " => " + " region = hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers.size());
}
@Test
void testRoute_Range_Pattern() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[user_id] = 1~100 " + " => " + " region=hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 =
new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers.size());
invocation.setAttachment("user_id", "80");
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers.size());
invocation.setAttachment("user_id", "101");
filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConditionStateRouterTestV31.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ConditionStateRouterTestV31.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.MultiDestConditionRouterRule;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConditionStateRouterTestV31 {
private static BitList<Invoker<String>> invokers;
@BeforeAll
public static void setUp() {
List<String> providerUrls = Arrays.asList(
"dubbo://127.0.0.1/com.foo.BarService",
"dubbo://127.0.0.1/com.foo.BarService",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=beijing&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://127.0.0.1/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService",
"dubbo://dubbo.apache.org/com.foo.BarService",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=beijing&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=gray",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal",
"dubbo://dubbo.apache.org/com.foo.BarService?region=hangzhou&env=normal");
List<Invoker<String>> invokerList = providerUrls.stream()
.map(url -> new MockInvoker<String>(URL.valueOf(url)))
.collect(Collectors.toList());
invokers = new BitList<>(invokerList);
}
@Test
public void testParseRawRule() {
String config =
"configVersion: v3.1\n" + "scope: service\n" + "force: false\n" + "runtime: true\n" + "enabled: true\n"
+ "key: shop\n" + "conditions:\n" + " - from:\n" + " match:\n" + " to:\n"
+ " - match: region=$region & version=v1\n"
+ " - match: region=$region & version=v2\n" + " weight: 200\n"
+ " - match: region=$region & version=v3\n" + " weight: 300\n" + " - from:\n"
+ " match: region=beijing & version=v1\n" + " to:\n"
+ " - match: env=$env & region=beijing\n";
AbstractRouterRule routerRule = ConditionRuleParser.parse(config);
Assertions.assertInstanceOf(MultiDestConditionRouterRule.class, routerRule);
MultiDestConditionRouterRule rule = (MultiDestConditionRouterRule) routerRule;
Assertions.assertEquals(rule.getConditions().size(), 2);
Assertions.assertEquals(rule.getConditions().get(0).getTo().size(), 3);
Assertions.assertEquals(rule.getConditions().get(1).getTo().size(), 1);
}
@Test
public void testMultiplyConditionRoute() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: com.foo.BarService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing&version=v1"),
invocation,
false,
new Holder<>());
int count = 0;
for (Invoker<String> invoker : invokers) {
String url = invoker.getUrl().toString();
if (url.contains("env") && !url.contains("gray")) {
count++;
}
}
Assertions.assertEquals(count, result.size());
}
@Test
public void testRemoveDuplicatesCondition() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
int count = 0;
for (Invoker<String> invoker : invokers) {
String url = invoker.getUrl().toString();
if (url.contains("env") && !url.contains("gray")) {
count++;
}
}
Assertions.assertEquals(count, result.size());
}
@Test
public void testConsequentCondition() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100\n"
+ " - from:\n"
+ " match: region=beijing\n"
+ " to:\n"
+ " - match: region=beijing\n"
+ " weight: 100\n"
+ " - from:\n"
+ " to:\n"
+ " - match: host!=127.0.0.1";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
int count = 0;
for (Invoker<String> invoker : invokers) {
String url = invoker.getUrl().toString();
if ((url.contains("env") && !url.contains("gray"))
&& url.contains("region=beijing")
&& !url.contains("127.0.0.1")) {
count++;
}
}
Assertions.assertEquals(count, result.size());
}
@Test
public void testUnMatchCondition() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env!=gray\n"
+ " to:\n"
+ " - match: env=gray\n"
+ " weight: 100\n"
+ " - from:\n"
+ " match: region!=beijing\n"
+ " to:\n"
+ " - match: region=beijing\n"
+ " weight: 100\n"
+ " - from:\n"
+ " to:\n"
+ " - match: host!=127.0.0.1";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
int count = 0;
for (Invoker<String> invoker : invokers) {
String url = invoker.getUrl().toString();
if (!url.contains("127.0.0.1")) {
count++;
}
}
Assertions.assertEquals(count, result.size());
}
@Test
public void testMatchAndRouteZero() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: true\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env=ErrTag\n"
+ " weight: 100\n"
+ " - from:\n"
+ " match: region!=beijing\n"
+ " to:\n"
+ " - match: region=beijing\n"
+ " weight: 100\n"
+ " - from:\n"
+ " to:\n"
+ " - match: host!=127.0.0.1";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, result.size());
}
@Test
public void testMatchRouteZeroAndIgnore() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: region=beijing\n"
+ " to:\n"
+ " - match: region!=beijing\n"
+ " weight: 100\n"
+ " - from:\n"
+ " to:\n"
+ " - match: host!=127.0.0.1\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env=ErrTag\n"
+ " weight: 100";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
int count = 0;
for (Invoker<String> invoker : invokers) {
String url = invoker.getUrl().toString();
if ((url.contains("region") && !url.contains("beijing") && !url.contains("127.0.0.1"))) {
count++;
}
}
Assertions.assertEquals(count, result.size());
}
@Test
public void testTrafficDisabledAndIgnoreConditionRouteForce() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: host=127.0.0.1\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100\n"
+ " - to:\n"
+ " - match: region!=beijing";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, result.size());
}
@Test
public void testMultiplyDestination() {
String rawRule = "configVersion: v3.1\n" + "scope: service\n"
+ "key: org.apache.dubbo.samples.CommentService\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "conditions:\n"
+ " - from:\n"
+ " match: env=gray\n"
+ " to:\n"
+ " - match: env!=gray\n"
+ " weight: 100\n"
+ " - match: env=gray\n"
+ " weight: 900\n"
+ " - from:\n"
+ " match: region=beijing\n"
+ " to:\n"
+ " - match: region!=beijing\n"
+ " weight: 100\n"
+ " - match: region=beijing\n"
+ " weight: 200";
ServiceStateRouter<String> router = new ServiceStateRouter<>(
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"));
router.process(new ConfigChangedEvent("com.foo.BarService", "", rawRule, ConfigChangeType.ADDED));
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getComment");
Map<Integer, Integer> actualDistribution = new HashMap<>();
for (int i = 0; i < 1000; i++) {
BitList<Invoker<String>> result = router.route(
invokers.clone(),
URL.valueOf("consumer://127.0.0.1/com.foo.BarService?env=gray®ion=beijing"),
invocation,
false,
new Holder<>());
actualDistribution.put(result.size(), actualDistribution.getOrDefault(result.size(), 0) + 1);
}
int sum = 0;
for (Map.Entry<Integer, Integer> entry : actualDistribution.entrySet()) {
sum += entry.getValue();
}
assertEquals(actualDistribution.size(), 4); // 8 6 4 2
Assertions.assertNotNull(actualDistribution.get(8));
Assertions.assertNotNull(actualDistribution.get(6));
Assertions.assertNotNull(actualDistribution.get(4));
Assertions.assertNotNull(actualDistribution.get(2));
assertEquals(sum, 1000);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
public class ProviderAppConditionStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private static final String RULE_SUFFIX = ".condition-router";
private static GovernanceRuleRepository ruleRepository;
private URL url = URL.valueOf("consumer://1.1.1.1/com.foo.BarService");
private String rawRule = "---\n" + "configVersion: v3.0\n"
+ "scope: application\n"
+ "force: true\n"
+ "runtime: false\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "conditions:\n"
+ "- method=sayHello => region=hangzhou\n"
+ "...";
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ruleRepository = Mockito.mock(GovernanceRuleRepository.class);
}
@Test
void test() {
ProviderAppStateRouter<String> router = new ProviderAppStateRouter<>(url);
router = Mockito.spy(router);
Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository);
Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP))
.thenReturn(rawRule);
// Mockito.when(ruleRepository.addListener()).thenReturn();
BitList<Invoker<String>> invokers = getInvokers();
router.notify(invokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
List<Invoker<String>> result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(1, result.size());
invocation.setMethodName("sayHi");
result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(3, result.size());
}
private BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider®ion=hangzhou"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.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.rpc.cluster.router.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Sets;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.mockito.Mockito.when;
class TagStateRouterTest {
private URL url;
private ModuleModel originModel;
private ModuleModel moduleModel;
@BeforeEach
public void setup() {
originModel = ApplicationModel.defaultModel().getDefaultModule();
moduleModel = Mockito.spy(originModel);
ScopeBeanFactory originBeanFactory = originModel.getBeanFactory();
ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory);
when(moduleModel.getBeanFactory()).thenReturn(beanFactory);
url = URL.valueOf("test://localhost/DemoInterface").setScopeModel(moduleModel);
}
@Test
void testTagRoutePickInvokers() {
StateRouter router = new TagStateRouterFactory().getRouter(TagRouterRule.class, url);
List<Invoker<String>> originInvokers = new ArrayList<>();
URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?dubbo.tag=tag2")
.setScopeModel(moduleModel);
URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface").setScopeModel(moduleModel);
URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface").setScopeModel(moduleModel);
Invoker<String> invoker1 = new MockInvoker<>(url1, true);
Invoker<String> invoker2 = new MockInvoker<>(url2, true);
Invoker<String> invoker3 = new MockInvoker<>(url3, true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setAttachment(TAG_KEY, "tag2");
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), invocation, false, new Holder<>());
Assertions.assertEquals(1, filteredInvokers.size());
Assertions.assertEquals(invoker1, filteredInvokers.get(0));
}
@Test
void testTagRouteWithDynamicRuleV3() {
TagStateRouter router = (TagStateRouter) new TagStateRouterFactory().getRouter(TagRouterRule.class, url);
router = Mockito.spy(router);
List<Invoker<String>> originInvokers = new ArrayList<>();
URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?application=foo&dubbo.tag=tag2&match_key=value")
.setScopeModel(moduleModel);
URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface?application=foo&match_key=value")
.setScopeModel(moduleModel);
URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface?application=foo")
.setScopeModel(moduleModel);
Invoker<String> invoker1 = new MockInvoker<>(url1, true);
Invoker<String> invoker2 = new MockInvoker<>(url2, true);
Invoker<String> invoker3 = new MockInvoker<>(url3, true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setAttachment(TAG_KEY, "tag2");
TagRouterRule rule = getTagRule();
Mockito.when(router.getInvokers()).thenReturn(invokers);
rule.init(router);
router.setTagRouterRule(rule);
List<Invoker<String>> filteredInvokers =
router.route(invokers, invokers.get(0).getUrl(), invocation, false, new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
// Assertions.(invoker1, filteredInvokers.get(0));
}
/**
* TagRouterRule parse test when the tags addresses is null
*
* <pre>
* ~ -> null
* null -> null
* </pre>
*/
@Test
void tagRouterRuleParseTest() {
String tagRouterRuleConfig = "---\n" + "force: false\n"
+ "runtime: true\n"
+ "enabled: false\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag1\n"
+ " addresses: null\n"
+ " - name: tag2\n"
+ " addresses: [\"30.5.120.37:20880\"]\n"
+ " - name: tag3\n"
+ " addresses: []\n"
+ " - name: tag4\n"
+ " addresses: ~\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
TagStateRouter<?> router = Mockito.mock(TagStateRouter.class);
Mockito.when(router.getInvokers()).thenReturn(BitList.emptyList());
tagRouterRule.init(router);
// assert tags
assert tagRouterRule.getKey().equals("demo-provider");
assert tagRouterRule.getPriority() == 1;
assert tagRouterRule.getTagNames().contains("tag1");
assert tagRouterRule.getTagNames().contains("tag2");
assert tagRouterRule.getTagNames().contains("tag3");
assert tagRouterRule.getTagNames().contains("tag4");
// assert addresses
assert tagRouterRule.getAddresses().contains("30.5.120.37:20880");
assert tagRouterRule.getTagnameToAddresses().get("tag1") == null;
assert tagRouterRule.getTagnameToAddresses().get("tag2").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag3") == null;
assert tagRouterRule.getTagnameToAddresses().get("tag4") == null;
assert tagRouterRule.getAddresses().size() == 1;
}
@Test
void tagRouterRuleParseTestV3() {
String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag1\n"
+ " match:\n"
+ " - key: match_key1\n"
+ " value:\n"
+ " exact: value1\n"
+ " - name: tag2\n"
+ " addresses:\n"
+ " - \"10.20.3.3:20880\"\n"
+ " - \"10.20.3.4:20880\"\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " exact: value2\n"
+ " - name: tag3\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " exact: value2\n"
+ " - name: tag4\n"
+ " match:\n"
+ " - key: not_exist\n"
+ " value:\n"
+ " exact: not_exist\n"
+ " - name: tag5\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " wildcard: \"*\"\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
TagStateRouter<String> router = Mockito.mock(TagStateRouter.class);
Mockito.when(router.getInvokers()).thenReturn(getInvokers());
tagRouterRule.init(router);
// assert tags
assert tagRouterRule.getKey().equals("demo-provider");
assert tagRouterRule.getPriority() == 1;
assert tagRouterRule.getTagNames().contains("tag1");
assert tagRouterRule.getTagNames().contains("tag2");
assert tagRouterRule.getTagNames().contains("tag3");
assert tagRouterRule.getTagNames().contains("tag4");
// assert addresses
assert tagRouterRule.getAddresses().size() == 2;
assert tagRouterRule.getAddresses().contains("10.20.3.3:20880");
assert tagRouterRule.getTagnameToAddresses().get("tag1").size() == 2;
assert tagRouterRule.getTagnameToAddresses().get("tag2").size() == 2;
assert tagRouterRule.getTagnameToAddresses().get("tag3").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag5").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag4") == null;
}
public BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?match_key1=value1&match_key2=value2"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.4:20880/com.foo.BarService?match_key1=value1"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
private TagRouterRule getTagRule() {
String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag2\n"
+ " match:\n"
+ " - key: match_key\n"
+ " value:\n"
+ " exact: value\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
return tagRouterRule;
}
@Test
public void tagMultiLevelTest() {
String tagSelector = "beta|team1|partner1";
Set<String> address1 = Sets.newHashSet("192.168.5.1:20880");
Map<String, Set<String>> tagAddresses = new HashMap<>();
tagAddresses.put("beta", address1);
Assertions.assertEquals(address1, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
Set<String> address2 = Sets.newHashSet("192.168.5.2:20880");
tagAddresses.put("beta|team1", address2);
Assertions.assertEquals(address2, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
Set<String> address3 = Sets.newHashSet("192.168.5.3:20880");
tagAddresses.put("beta|team1|partner1", address3);
Assertions.assertEquals(address3, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta";
Assertions.assertEquals(address1, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta|team1";
Assertions.assertEquals(address2, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta|team1|partner1";
Assertions.assertEquals(address3, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta2";
Assertions.assertNull(TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta|team2";
Assertions.assertEquals(address1, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
tagSelector = "beta|team1|partner2";
Assertions.assertEquals(address2, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false));
}
@Test
public void tagLevelForceTest() {
Set<String> addresses = Sets.newHashSet("192.168.1.223:20880");
Map<String, Set<String>> tagAddresses = new HashMap<>();
tagAddresses.put("beta", addresses);
Set<String> selectedAddresses = TagStateRouter.selectAddressByTagLevel(tagAddresses, "beta", true);
Assertions.assertEquals(addresses, selectedAddresses);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.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.rpc.cluster.router.mesh.util;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MeshRuleDispatcherTest {
@Test
void post() {
MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp");
Map<String, List<Map<String, Object>>> ruleMap = new HashMap<>();
List<Map<String, Object>> type1 = new LinkedList<>();
List<Map<String, Object>> type2 = new LinkedList<>();
List<Map<String, Object>> type3 = new LinkedList<>();
ruleMap.put("Type1", type1);
ruleMap.put("Type2", type2);
ruleMap.put("Type3", type3);
AtomicInteger count = new AtomicInteger(0);
MeshRuleListener listener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.assertEquals("TestApp", appName);
Assertions.assertEquals(System.identityHashCode(type1), System.identityHashCode(rules));
count.incrementAndGet();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
MeshRuleListener listener2 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.assertEquals("TestApp", appName);
Assertions.assertEquals(System.identityHashCode(type2), System.identityHashCode(rules));
count.incrementAndGet();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type2";
}
};
MeshRuleListener listener4 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.fail();
}
@Override
public void clearRule(String appName) {
Assertions.assertEquals("TestApp", appName);
count.incrementAndGet();
}
@Override
public String ruleSuffix() {
return "Type4";
}
};
meshRuleDispatcher.register(listener1);
meshRuleDispatcher.register(listener2);
meshRuleDispatcher.register(listener4);
meshRuleDispatcher.post(ruleMap);
Assertions.assertEquals(3, count.get());
}
@Test
void register() {
MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp");
MeshRuleListener listener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
meshRuleDispatcher.register(listener1);
meshRuleDispatcher.register(listener1);
Assertions.assertEquals(
1, meshRuleDispatcher.getListenerMap().get("Type1").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1));
}
@Test
void unregister() {
MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp");
MeshRuleListener listener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
MeshRuleListener listener2 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
MeshRuleListener listener3 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type2";
}
};
meshRuleDispatcher.register(listener1);
meshRuleDispatcher.register(listener2);
meshRuleDispatcher.register(listener3);
Assertions.assertEquals(
2, meshRuleDispatcher.getListenerMap().get("Type1").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1));
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2));
Assertions.assertEquals(
1, meshRuleDispatcher.getListenerMap().get("Type2").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3));
meshRuleDispatcher.unregister(listener1);
Assertions.assertEquals(
1, meshRuleDispatcher.getListenerMap().get("Type1").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2));
Assertions.assertEquals(
1, meshRuleDispatcher.getListenerMap().get("Type2").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3));
meshRuleDispatcher.unregister(listener2);
Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type1"));
Assertions.assertEquals(
1, meshRuleDispatcher.getListenerMap().get("Type2").size());
Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3));
meshRuleDispatcher.unregister(listener3);
Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type1"));
Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type2"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.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.rpc.cluster.router.mesh.rule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRoute;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRouteDetail;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
class VirtualServiceRuleTest {
@Test
void parserTest() {
Yaml yaml = new Yaml();
VirtualServiceRule virtualServiceRule = yaml.loadAs(
this.getClass().getClassLoader().getResourceAsStream("VirtualServiceTest.yaml"),
VirtualServiceRule.class);
assertNotNull(virtualServiceRule);
assertEquals("service.dubbo.apache.org/v1alpha1", virtualServiceRule.getApiVersion());
assertEquals("VirtualService", virtualServiceRule.getKind());
assertEquals("demo-route", virtualServiceRule.getMetadata().get("name"));
List<String> hosts = virtualServiceRule.getSpec().getHosts();
assertEquals(1, hosts.size());
assertEquals("demo", hosts.get(0));
List<DubboRoute> dubboRoutes = virtualServiceRule.getSpec().getDubbo();
assertEquals(1, dubboRoutes.size());
DubboRoute dubboRoute = dubboRoutes.get(0);
assertNull(dubboRoute.getName());
assertEquals(1, dubboRoute.getServices().size());
assertEquals("ccc", dubboRoute.getServices().get(0).getRegex());
List<DubboRouteDetail> routedetail = dubboRoute.getRoutedetail();
DubboRouteDetail firstDubboRouteDetail = routedetail.get(0);
DubboRouteDetail secondDubboRouteDetail = routedetail.get(1);
DubboRouteDetail thirdDubboRouteDetail = routedetail.get(2);
assertEquals("xxx-project", firstDubboRouteDetail.getName());
assertEquals(
"xxx", firstDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel"));
assertEquals(
"demo", firstDubboRouteDetail.getRoute().get(0).getDestination().getHost());
assertEquals(
"isolation",
firstDubboRouteDetail.getRoute().get(0).getDestination().getSubset());
assertEquals("testing-trunk", secondDubboRouteDetail.getName());
assertEquals(
"testing-trunk",
secondDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel"));
assertEquals(
"demo",
secondDubboRouteDetail.getRoute().get(0).getDestination().getHost());
assertEquals(
"testing-trunk",
secondDubboRouteDetail.getRoute().get(0).getDestination().getSubset());
assertEquals("testing", thirdDubboRouteDetail.getName());
assertNull(thirdDubboRouteDetail.getMatch());
assertEquals(
"demo", thirdDubboRouteDetail.getRoute().get(0).getDestination().getHost());
assertEquals(
"testing",
thirdDubboRouteDetail.getRoute().get(0).getDestination().getSubset());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.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.rpc.cluster.router.mesh.rule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.SimpleLB;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.DESTINATION_RULE_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.KIND_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.VIRTUAL_SERVICE_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class DestinationRuleTest {
@Test
void parserTest() {
Yaml yaml = new Yaml();
DestinationRule destinationRule = yaml.loadAs(
this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest.yaml"),
DestinationRule.class);
// apiVersion: service.dubbo.apache.org/v1alpha1
// kind: DestinationRule
// metadata: { name: demo-route }
// spec:
// host: demo
// subsets:
// - labels: { env-sign: xxx,tag1: hello }
// name: isolation
// - labels: { env-sign: yyy }
// name: testing-trunk
// - labels: { env-sign: zzz }
// name: testing
assertEquals("service.dubbo.apache.org/v1alpha1", destinationRule.getApiVersion());
assertEquals(DESTINATION_RULE_KEY, destinationRule.getKind());
assertEquals("demo-route", destinationRule.getMetadata().get("name"));
assertEquals("demo", destinationRule.getSpec().getHost());
assertEquals(3, destinationRule.getSpec().getSubsets().size());
assertEquals("isolation", destinationRule.getSpec().getSubsets().get(0).getName());
assertEquals(
2, destinationRule.getSpec().getSubsets().get(0).getLabels().size());
assertEquals(
"xxx", destinationRule.getSpec().getSubsets().get(0).getLabels().get("env-sign"));
assertEquals(
"hello",
destinationRule.getSpec().getSubsets().get(0).getLabels().get("tag1"));
assertEquals(
"testing-trunk", destinationRule.getSpec().getSubsets().get(1).getName());
assertEquals(
1, destinationRule.getSpec().getSubsets().get(1).getLabels().size());
assertEquals(
"yyy", destinationRule.getSpec().getSubsets().get(1).getLabels().get("env-sign"));
assertEquals("testing", destinationRule.getSpec().getSubsets().get(2).getName());
assertEquals(
1, destinationRule.getSpec().getSubsets().get(2).getLabels().size());
assertEquals(
"zzz", destinationRule.getSpec().getSubsets().get(2).getLabels().get("env-sign"));
assertEquals(
SimpleLB.ROUND_ROBIN,
destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple());
assertEquals(
null,
destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash());
}
@Test
void parserMultiRuleTest() {
Yaml yaml = new Yaml();
Yaml yaml2 = new Yaml();
Iterable objectIterable =
yaml.loadAll(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest2.yaml"));
for (Object result : objectIterable) {
Map resultMap = (Map) result;
if (resultMap.get("kind").equals(DESTINATION_RULE_KEY)) {
DestinationRule destinationRule = yaml2.loadAs(yaml2.dump(result), DestinationRule.class);
assertNotNull(destinationRule);
} else if (resultMap.get(KIND_KEY).equals(VIRTUAL_SERVICE_KEY)) {
VirtualServiceRule virtualServiceRule = yaml2.loadAs(yaml2.dump(result), VirtualServiceRule.class);
assertNotNull(virtualServiceRule);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.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.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboAttachmentMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboMethodMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboMatchRequestTest {
@Test
void isMatch() {
DubboMatchRequest dubboMatchRequest = new DubboMatchRequest();
// methodMatch
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
StringMatch nameStringMatch = new StringMatch();
nameStringMatch.setExact("sayHello");
dubboMethodMatch.setName_match(nameStringMatch);
dubboMatchRequest.setMethod(dubboMethodMatch);
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setMethodName("sayHello");
assertTrue(dubboMatchRequest.isMatch(rpcInvocation, new HashMap<>(), Collections.emptySet()));
rpcInvocation.setMethodName("satHi");
assertFalse(dubboMatchRequest.isMatch(rpcInvocation, new HashMap<>(), Collections.emptySet()));
// sourceLabels
Map<String, String> sourceLabels = new HashMap<>();
sourceLabels.put("key1", "value1");
sourceLabels.put("key2", "value2");
dubboMatchRequest.setSourceLabels(sourceLabels);
Map<String, String> inputSourceLabelsMap = new HashMap<>();
inputSourceLabelsMap.put("key1", "value1");
inputSourceLabelsMap.put("key2", "value2");
inputSourceLabelsMap.put("key3", "value3");
Map<String, String> inputSourceLabelsMap2 = new HashMap<>();
inputSourceLabelsMap2.put("key1", "other");
inputSourceLabelsMap2.put("key2", "value2");
inputSourceLabelsMap2.put("key3", "value3");
rpcInvocation.setMethodName("sayHello");
assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.emptySet()));
assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap2, Collections.emptySet()));
// tracingContext
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
dubboMatchRequest.setAttachments(dubboAttachmentMatch);
Map<String, String> invokeTracingContextMap = new HashMap<>();
invokeTracingContextMap.put("name", "qinliujie");
invokeTracingContextMap.put("machineGroup", "test_host");
invokeTracingContextMap.put("other", "other");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeTracingContextMap.get(key);
assertTrue(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("name", "jack");
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key);
assertFalse(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider2)));
// dubbo context
dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> eagleeyecontextMatchMap = new HashMap<>();
nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
eagleeyecontextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(eagleeyecontextMatchMap);
Map<String, StringMatch> dubboContextMatchMap = new HashMap<>();
StringMatch dpathMatch = new StringMatch();
dpathMatch.setExact("PRE");
dubboContextMatchMap.put("dpath", dpathMatch);
dubboAttachmentMatch.setDubboContext(dubboContextMatchMap);
dubboMatchRequest.setAttachments(dubboAttachmentMatch);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("dpath", "PRE");
rpcInvocation.setAttachments(invokeDubboContextMap);
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap.get(key);
assertTrue(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3)));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
invokeDubboContextMap.put("dpath", "other");
rpcInvocation.setAttachments(invokeDubboContextMap2);
assertFalse(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListDoubleMatchTest {
@Test
void isMatch() {
ListDoubleMatch listDoubleMatch = new ListDoubleMatch();
List<DoubleMatch> oneof = new ArrayList<>();
DoubleMatch doubleMatch1 = new DoubleMatch();
doubleMatch1.setExact(10.0);
DoubleMatch doubleMatch2 = new DoubleMatch();
doubleMatch2.setExact(11.0);
oneof.add(doubleMatch1);
oneof.add(doubleMatch2);
listDoubleMatch.setOneof(oneof);
assertTrue(listDoubleMatch.isMatch(10.0));
assertTrue(listDoubleMatch.isMatch(11.0));
assertFalse(listDoubleMatch.isMatch(12.0));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListStringMatchTest {
@Test
void isMatch() {
ListStringMatch listStringMatch = new ListStringMatch();
List<StringMatch> oneof = new ArrayList<>();
StringMatch stringMatch1 = new StringMatch();
stringMatch1.setExact("1");
StringMatch stringMatch2 = new StringMatch();
stringMatch2.setExact("2");
oneof.add(stringMatch1);
oneof.add(stringMatch2);
listStringMatch.setOneof(oneof);
assertTrue(listStringMatch.isMatch("1"));
assertTrue(listStringMatch.isMatch("2"));
assertFalse(listStringMatch.isMatch("3"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StringMatchTest {
@Test
void exactMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setExact("qinliujie");
assertTrue(stringMatch.isMatch("qinliujie"));
assertFalse(stringMatch.isMatch("other"));
assertFalse(stringMatch.isMatch(null));
}
@Test
void prefixMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setPrefix("org.apache.dubbo.rpc.cluster.router.mesh");
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh.test"));
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch(null));
}
@Test
void regxMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setRegex("org.apache.dubbo.rpc.cluster.router.mesh.*");
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh"));
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh.test"));
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch("com.taobao"));
}
@Test
void emptyMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setEmpty("empty");
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertTrue(stringMatch.isMatch(""));
assertTrue(stringMatch.isMatch(null));
}
@Test
void noEmptyMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setNoempty("noempty");
assertTrue(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch(""));
assertFalse(stringMatch.isMatch(null));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DoubleMatchTest {
@Test
void exactMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
doubleMatch.setExact(10.0);
assertTrue(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(9.0));
}
@Test
void rangeStartMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setStart(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertTrue(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(9.0));
}
@Test
void rangeEndMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setEnd(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertFalse(doubleMatch.isMatch(10.0));
assertTrue(doubleMatch.isMatch(9.0));
}
@Test
void rangeStartEndMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setStart(5.0);
doubleRangeMatch.setEnd(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertTrue(doubleMatch.isMatch(5.0));
assertFalse(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(4.9));
assertFalse(doubleMatch.isMatch(10.1));
assertTrue(doubleMatch.isMatch(6.0));
}
@Test
void modMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
doubleMatch.setMod(2.0);
doubleMatch.setExact(3.0);
assertFalse(doubleMatch.isMatch(3.0));
doubleMatch.setExact(1.0);
assertTrue(doubleMatch.isMatch(1.0));
assertFalse(doubleMatch.isMatch(2.0));
assertTrue(doubleMatch.isMatch(3.0));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListBoolMatchTest {
@Test
void isMatch() {
ListBoolMatch listBoolMatch = new ListBoolMatch();
List<BoolMatch> oneof = new ArrayList<>();
BoolMatch boolMatch1 = new BoolMatch();
boolMatch1.setExact(true);
oneof.add(boolMatch1);
listBoolMatch.setOneof(oneof);
assertTrue(listBoolMatch.isMatch(true));
assertFalse(listBoolMatch.isMatch(false));
BoolMatch boolMatch2 = new BoolMatch();
boolMatch2.setExact(false);
oneof.add(boolMatch2);
listBoolMatch.setOneof(oneof);
assertTrue(listBoolMatch.isMatch(false));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboAttachmentMatchTest {
@Test
void dubboContextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> dubbocontextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
dubbocontextMatchMap.put("name", nameMatch);
StringMatch machineGroupMatch = new StringMatch();
machineGroupMatch.setExact("test_host");
dubbocontextMatchMap.put("machineGroup", machineGroupMatch);
dubboAttachmentMatch.setDubboContext(dubbocontextMatchMap);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("name", "qinliujie");
invokeDubboContextMap.put("machineGroup", "test_host");
invokeDubboContextMap.put("other", "other");
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setAttachments(invokeDubboContextMap);
assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.emptySet()));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
invokeDubboContextMap2.put("name", "jack");
invokeDubboContextMap2.put("machineGroup", "test_host");
invokeDubboContextMap2.put("other", "other");
RpcInvocation rpcInvocation2 = new RpcInvocation();
rpcInvocation2.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.emptySet()));
Map<String, String> invokeDubboContextMap3 = new HashMap<>();
invokeDubboContextMap3.put("name", "qinliujie");
invokeDubboContextMap3.put("machineGroup", "my_host");
invokeDubboContextMap3.put("other", "other");
RpcInvocation rpcInvocation3 = new RpcInvocation();
rpcInvocation3.setAttachments(invokeDubboContextMap3);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.emptySet()));
}
@Test
void tracingContextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
StringMatch machineGroupMatch = new StringMatch();
machineGroupMatch.setExact("test_host");
tracingContextMatchMap.put("machineGroup", machineGroupMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
Map<String, String> invokeEagleEyeContextMap = new HashMap<>();
invokeEagleEyeContextMap.put("name", "qinliujie");
invokeEagleEyeContextMap.put("machineGroup", "test_host");
invokeEagleEyeContextMap.put("other", "other");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeEagleEyeContextMap.get(key);
assertTrue(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("name", "jack");
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key);
assertFalse(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider2)));
Map<String, String> invokeEagleEyeContextMap3 = new HashMap<>();
invokeEagleEyeContextMap3.put("name", "qinliujie");
invokeEagleEyeContextMap3.put("machineGroup", "my_host");
invokeEagleEyeContextMap3.put("other", "other");
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeEagleEyeContextMap3.get(key);
assertFalse(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider3)));
}
@Test
void contextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
Map<String, String> invokeTracingContextMap = new HashMap<>();
invokeTracingContextMap.put("name", "qinliujie");
invokeTracingContextMap.put("machineGroup", "test_host");
invokeTracingContextMap.put("other", "other");
Map<String, StringMatch> dubboContextMatchMap = new HashMap<>();
StringMatch dpathMatch = new StringMatch();
dpathMatch.setExact("PRE");
dubboContextMatchMap.put("dpath", dpathMatch);
dubboAttachmentMatch.setDubboContext(dubboContextMatchMap);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("dpath", "PRE");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setAttachments(invokeDubboContextMap);
assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap1 = new HashMap<>();
invokeTracingContextMap1.put("name", "jack");
invokeTracingContextMap1.put("machineGroup", "test_host");
invokeTracingContextMap1.put("other", "other");
TracingContextProvider tracingContextProvider1 = (invocation, key) -> invokeTracingContextMap1.get(key);
RpcInvocation rpcInvocation1 = new RpcInvocation();
rpcInvocation1.setAttachments(invokeDubboContextMap);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation1, Collections.singleton(tracingContextProvider1)));
Map<String, String> invokeDubboContextMap1 = new HashMap<>();
invokeDubboContextMap1.put("dpath", "PRE-2");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation2 = new RpcInvocation();
rpcInvocation2.setAttachments(invokeDubboContextMap1);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.singleton(tracingContextProvider2)));
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap1.get(key);
RpcInvocation rpcInvocation3 = new RpcInvocation();
rpcInvocation3.setAttachments(invokeDubboContextMap1);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.singleton(tracingContextProvider3)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider4 = (invocation, key) -> invokeTracingContextMap2.get(key);
RpcInvocation rpcInvocation4 = new RpcInvocation();
rpcInvocation4.setAttachments(invokeDubboContextMap);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation4, Collections.singleton(tracingContextProvider4)));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
TracingContextProvider tracingContextProvider5 = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation5 = new RpcInvocation();
rpcInvocation5.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation5, Collections.singleton(tracingContextProvider5)));
TracingContextProvider tracingContextProvider6 = (invocation, key) -> invokeTracingContextMap2.get(key);
RpcInvocation rpcInvocation6 = new RpcInvocation();
rpcInvocation5.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation6, Collections.singleton(tracingContextProvider6)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.RpcInvocation;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboMethodMatchTest {
@Test
void nameMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
StringMatch nameStringMatch = new StringMatch();
nameStringMatch.setExact("sayHello");
dubboMethodMatch.setName_match(nameStringMatch);
assertTrue(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
}
@Test
void argcMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
dubboMethodMatch.setArgc(1);
assertFalse(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
assertTrue(dubboMethodMatch.isMatch(
new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {"1"})));
}
@Test
void argpMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
List<StringMatch> argpMatch = new ArrayList<>();
StringMatch first = new StringMatch();
first.setExact("java.lang.Long");
StringMatch second = new StringMatch();
second.setRegex(".*");
argpMatch.add(first);
argpMatch.add(second);
dubboMethodMatch.setArgp(argpMatch);
assertTrue(dubboMethodMatch.isMatch(
new RpcInvocation(null, "sayHello", "", "", new Class[] {Long.class, String.class}, new Object[] {})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "sayHello", "", "", new Class[] {Long.class, String.class, String.class}, new Object[] {})));
assertFalse(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
}
@Test
void parametersMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
List<DubboMethodArg> parametersMatch = new ArrayList<>();
// ----- index 0
{
DubboMethodArg dubboMethodArg0 = new DubboMethodArg();
dubboMethodArg0.setIndex(0);
ListDoubleMatch listDoubleMatch = new ListDoubleMatch();
List<DoubleMatch> oneof = new ArrayList<>();
DoubleMatch doubleMatch1 = new DoubleMatch();
doubleMatch1.setExact(10.0);
oneof.add(doubleMatch1);
listDoubleMatch.setOneof(oneof);
dubboMethodArg0.setNum_value(listDoubleMatch);
parametersMatch.add(dubboMethodArg0);
}
// -----index 1
{
DubboMethodArg dubboMethodArg1 = new DubboMethodArg();
dubboMethodArg1.setIndex(1);
ListStringMatch listStringMatch = new ListStringMatch();
List<StringMatch> oneof = new ArrayList<>();
StringMatch stringMatch1 = new StringMatch();
stringMatch1.setExact("sayHello");
oneof.add(stringMatch1);
listStringMatch.setOneof(oneof);
dubboMethodArg1.setStr_value(listStringMatch);
parametersMatch.add(dubboMethodArg1);
}
dubboMethodMatch.setArgs(parametersMatch);
assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHello"})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHi"})));
// -----index 2
{
DubboMethodArg dubboMethodArg2 = new DubboMethodArg();
dubboMethodArg2.setIndex(2);
BoolMatch boolMatch = new BoolMatch();
boolMatch.setExact(true);
dubboMethodArg2.setBool_value(boolMatch);
parametersMatch.add(dubboMethodArg2);
}
assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] {
10, "sayHello", true
})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] {
10, "sayHello", false
})));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BoolMatchTest {
@Test
void isMatch() {
BoolMatch boolMatch = new BoolMatch();
boolMatch.setExact(true);
assertTrue(boolMatch.isMatch(true));
assertFalse(boolMatch.isMatch(false));
boolMatch.setExact(false);
assertFalse(boolMatch.isMatch(true));
assertTrue(boolMatch.isMatch(false));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class MeshRuleRouterTest {
private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " host: demo\n"
+ " subsets:\n"
+ " - labels: { env-sign: xxx, tag1: hello }\n"
+ " name: isolation\n"
+ " - labels: { env-sign: yyy }\n"
+ " name: testing-trunk\n"
+ " - labels: { env-sign: zzz }\n"
+ " name: testing\n"
+ " trafficPolicy:\n"
+ " loadBalancer: { simple: ROUND_ROBIN }\n"
+ "\n";
private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " dubbo:\n"
+ " - routedetail:\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: xxx}}\n"
+ " name: xxx-project\n"
+ " route:\n"
+ " - destination: {host: demo, subset: isolation}\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: testing-trunk}}\n"
+ " name: testing-trunk\n"
+ " route:\n"
+ " - destination:\n"
+ " host: demo\n"
+ " subset: testing-trunk\n"
+ " fallback:\n"
+ " host: demo\n"
+ " subset: testing\n"
+ " - name: testing\n"
+ " route:\n"
+ " - destination: {host: demo, subset: testing}\n"
+ " services:\n"
+ " - {regex: ccc}\n"
+ " hosts: [demo]\n";
private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " dubbo:\n"
+ " - routedetail:\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: xxx}}\n"
+ " name: xxx-project\n"
+ " route:\n"
+ " - destination: {host: demo, subset: isolation}\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: testing-trunk}}\n"
+ " name: testing-trunk\n"
+ " route:\n"
+ " - destination:\n"
+ " host: demo\n"
+ " subset: testing-trunk\n"
+ " fallback:\n"
+ " host: demo\n"
+ " subset: testing\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: testing}}\n"
+ " name: testing\n"
+ " route:\n"
+ " - destination: {host: demo, subset: testing}\n"
+ " hosts: [demo]\n";
private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " dubbo:\n"
+ " - routedetail:\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: xxx}}\n"
+ " name: xxx-project\n"
+ " route:\n"
+ " - destination: {host: demo, subset: isolation}\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: testing-trunk}}\n"
+ " name: testing-trunk\n"
+ " route:\n"
+ " - destination:\n"
+ " host: demo\n"
+ " subset: testing-trunk\n"
+ " fallback:\n"
+ " destination:\n"
+ " host: demo\n"
+ " subset: testing\n"
+ " - weight: 10\n"
+ " destination:\n"
+ " host: demo\n"
+ " subset: isolation\n"
+ " - match:\n"
+ " - attachments: \n"
+ " dubboContext: {trafficLabel: {regex: testing}}\n"
+ " name: testing\n"
+ " route:\n"
+ " - destination: {host: demo, subset: testing}\n"
+ " hosts: [demo]\n";
private ModuleModel originModel;
private ModuleModel moduleModel;
private MeshRuleManager meshRuleManager;
private Set<TracingContextProvider> tracingContextProviders;
private URL url;
@BeforeEach
public void setup() {
originModel = ApplicationModel.defaultModel().getDefaultModule();
moduleModel = Mockito.spy(originModel);
ScopeBeanFactory originBeanFactory = originModel.getBeanFactory();
ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory);
when(moduleModel.getBeanFactory()).thenReturn(beanFactory);
meshRuleManager = Mockito.mock(MeshRuleManager.class);
when(beanFactory.getBean(MeshRuleManager.class)).thenReturn(meshRuleManager);
ExtensionLoader<TracingContextProvider> extensionLoader = Mockito.mock(ExtensionLoader.class);
tracingContextProviders = new HashSet<>();
when(extensionLoader.getSupportedExtensionInstances()).thenReturn(tracingContextProviders);
when(moduleModel.getExtensionLoader(TracingContextProvider.class)).thenReturn(extensionLoader);
url = URL.valueOf("test://localhost/DemoInterface").setScopeModel(moduleModel);
}
@AfterEach
public void teardown() {
originModel.destroy();
}
private Invoker<Object> createInvoker(String app) {
URL url = URL.valueOf(
"dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app));
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.getUrl()).thenReturn(url);
return invoker;
}
private Invoker<Object> createInvoker(Map<String, String> parameters) {
URL url = URL.valueOf("dubbo://localhost/DemoInterface?remote.application=app1")
.addParameters(parameters);
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.getUrl()).thenReturn(url);
return invoker;
}
@Test
void testNotify() {
StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url);
meshRuleRouter.notify(null);
assertEquals(0, meshRuleRouter.getRemoteAppName().size());
BitList<Invoker<Object>> invokers =
new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1")));
meshRuleRouter.notify(invokers);
assertEquals(1, meshRuleRouter.getRemoteAppName().size());
assertTrue(meshRuleRouter.getRemoteAppName().contains("app1"));
assertEquals(invokers, meshRuleRouter.getInvokerList());
verify(meshRuleManager, times(1)).register("app1", meshRuleRouter);
invokers = new BitList<>(Arrays.asList(createInvoker("unknown"), createInvoker("app2")));
meshRuleRouter.notify(invokers);
verify(meshRuleManager, times(1)).register("app2", meshRuleRouter);
verify(meshRuleManager, times(1)).unregister("app1", meshRuleRouter);
assertEquals(invokers, meshRuleRouter.getInvokerList());
meshRuleRouter.stop();
verify(meshRuleManager, times(1)).unregister("app2", meshRuleRouter);
}
@Test
void testRuleChange() {
StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
List<Map<String, Object>> rules = new LinkedList<>();
rules.add(yaml.load(rule1));
meshRuleRouter.onRuleChange("app1", rules);
assertEquals(0, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size());
rules.add(yaml.load(rule2));
meshRuleRouter.onRuleChange("app1", rules);
assertEquals(1, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size());
assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app1"));
meshRuleRouter.onRuleChange("app2", rules);
assertEquals(2, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size());
assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app1"));
assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app2"));
meshRuleRouter.clearRule("app1");
assertEquals(1, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size());
assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app2"));
}
@Test
void testRoute1() {
StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url);
BitList<Invoker<Object>> invokers =
new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1")));
assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, null, false, null));
Holder<String> message = new Holder<>();
meshRuleRouter.doRoute(invokers.clone(), null, null, true, null, message);
assertEquals("MeshRuleCache has not been built. Skip route.", message.get());
}
@Test
void testRoute2() {
StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
List<Map<String, Object>> rules = new LinkedList<>();
rules.add(yaml.load(rule1));
rules.add(yaml.load(rule2));
meshRuleRouter.onRuleChange("app1", rules);
Invoker<Object> isolation = createInvoker(new HashMap<String, String>() {
{
put("env-sign", "xxx");
put("tag1", "hello");
}
});
Invoker<Object> testingTrunk = createInvoker(Collections.singletonMap("env-sign", "yyy"));
Invoker<Object> testing = createInvoker(Collections.singletonMap("env-sign", "zzz"));
BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(isolation, testingTrunk, testing));
meshRuleRouter.notify(invokers);
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setServiceName("ccc");
rpcInvocation.setAttachment("trafficLabel", "xxx");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
isolation,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
Holder<String> message = new Holder<>();
meshRuleRouter.doRoute(invokers.clone(), null, rpcInvocation, true, null, message);
assertEquals("Match App: app1 Subset: isolation ", message.get());
rpcInvocation.setAttachment("trafficLabel", "testing-trunk");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testingTrunk,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setAttachment("trafficLabel", null);
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testing,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setServiceName("aaa");
assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null));
message = new Holder<>();
meshRuleRouter.doRoute(invokers.clone(), null, rpcInvocation, true, null, message);
assertEquals("Empty protection after routed.", message.get());
rules = new LinkedList<>();
rules.add(yaml.load(rule1));
rules.add(yaml.load(rule3));
meshRuleRouter.onRuleChange("app1", rules);
rpcInvocation.setServiceName("ccc");
rpcInvocation.setAttachment("trafficLabel", "xxx");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
isolation,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setAttachment("trafficLabel", "testing-trunk");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testingTrunk,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setAttachment("trafficLabel", "testing");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testing,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setServiceName("aaa");
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testing,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
rpcInvocation.setAttachment("trafficLabel", null);
assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null));
rules = new LinkedList<>();
rules.add(yaml.load(rule1));
rules.add(yaml.load(rule4));
meshRuleRouter.onRuleChange("app1", rules);
rpcInvocation.setAttachment("trafficLabel", "testing-trunk");
int testingCount = 0;
int isolationCount = 0;
for (int i = 0; i < 1000; i++) {
BitList<Invoker<Object>> result = meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null);
assertEquals(1, result.size());
if (result.contains(testing)) {
testingCount++;
} else {
isolationCount++;
}
}
assertTrue(isolationCount > testingCount * 10);
invokers.removeAll(Arrays.asList(isolation, testingTrunk));
for (int i = 0; i < 1000; i++) {
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testing,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
}
meshRuleRouter.notify(invokers);
for (int i = 0; i < 1000; i++) {
assertEquals(
1,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.size());
assertEquals(
testing,
meshRuleRouter
.route(invokers.clone(), null, rpcInvocation, false, null)
.get(0));
}
Invoker<Object> mock = createInvoker(Collections.singletonMap("env-sign", "mock"));
invokers = new BitList<>(Arrays.asList(isolation, testingTrunk, testing, mock));
meshRuleRouter.notify(invokers);
invokers.removeAll(Arrays.asList(isolation, testingTrunk, testing));
assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class MeshRuleManagerTest {
private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route.Type1 }\n"
+ "spec:\n"
+ " host: demo\n"
+ "\n";
private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route.Type1 }\n"
+ "spec:\n"
+ " hosts: [demo]\n";
private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route.Type2 }\n"
+ "spec:\n"
+ " host: demo\n"
+ "\n";
private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route.Type2 }\n"
+ "spec:\n"
+ " hosts: [demo]\n";
private ModuleModel originModule;
private ModuleModel moduleModel;
private GovernanceRuleRepository ruleRepository;
private Set<MeshEnvListenerFactory> envListenerFactories;
@BeforeEach
public void setup() {
originModule = ApplicationModel.defaultModel().getDefaultModule();
moduleModel = Mockito.spy(originModule);
ruleRepository = Mockito.mock(GovernanceRuleRepository.class);
when(moduleModel.getDefaultExtension(GovernanceRuleRepository.class)).thenReturn(ruleRepository);
ExtensionLoader<MeshEnvListenerFactory> envListenerFactoryLoader = Mockito.mock(ExtensionLoader.class);
envListenerFactories = new HashSet<>();
when(envListenerFactoryLoader.getSupportedExtensionInstances()).thenReturn(envListenerFactories);
when(moduleModel.getExtensionLoader(MeshEnvListenerFactory.class)).thenReturn(envListenerFactoryLoader);
}
@AfterEach
public void teardown() {
originModule.destroy();
}
@Test
void testRegister1() {
MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel);
MeshRuleListener meshRuleListener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
fail();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
meshRuleManager.register("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L);
MeshAppRuleListener meshAppRuleListener =
meshRuleManager.getAppRuleListeners().values().iterator().next();
verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener);
meshRuleManager.register("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
MeshRuleListener meshRuleListener2 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
fail();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type2";
}
};
meshRuleManager.register("dubbo-demo", meshRuleListener2);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
assertEquals(
2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size());
meshRuleManager.unregister("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
assertEquals(
1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size());
meshRuleManager.unregister("dubbo-demo", meshRuleListener2);
assertEquals(0, meshRuleManager.getAppRuleListeners().size());
verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener);
}
@Test
void testRegister2() {
MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel);
AtomicInteger invokeTimes = new AtomicInteger(0);
MeshRuleListener meshRuleListener = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
assertEquals("dubbo-demo", appName);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
assertTrue(rules.contains(yaml.load(rule1)));
assertTrue(rules.contains(yaml.load(rule2)));
invokeTimes.incrementAndGet();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
when(ruleRepository.getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L)).thenReturn(rule1 + "---\n" + rule2);
meshRuleManager.register("dubbo-demo", meshRuleListener);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L);
verify(ruleRepository, times(1))
.addListener(
"dubbo-demo.MESHAPPRULE",
"dubbo",
meshRuleManager
.getAppRuleListeners()
.values()
.iterator()
.next());
assertEquals(1, invokeTimes.get());
meshRuleManager.register("dubbo-demo", meshRuleListener);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
}
@Test
void testRegister3() {
MeshEnvListenerFactory meshEnvListenerFactory1 = Mockito.mock(MeshEnvListenerFactory.class);
MeshEnvListenerFactory meshEnvListenerFactory2 = Mockito.mock(MeshEnvListenerFactory.class);
MeshEnvListener meshEnvListener1 = Mockito.mock(MeshEnvListener.class);
when(meshEnvListenerFactory1.getListener()).thenReturn(meshEnvListener1);
MeshEnvListener meshEnvListener2 = Mockito.mock(MeshEnvListener.class);
when(meshEnvListenerFactory2.getListener()).thenReturn(meshEnvListener2);
envListenerFactories.add(meshEnvListenerFactory1);
envListenerFactories.add(meshEnvListenerFactory2);
MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel);
MeshRuleListener meshRuleListener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
fail();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
when(meshEnvListener1.isEnable()).thenReturn(false);
when(meshEnvListener2.isEnable()).thenReturn(true);
meshRuleManager.register("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L);
MeshAppRuleListener meshAppRuleListener =
meshRuleManager.getAppRuleListeners().values().iterator().next();
verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener);
verify(meshEnvListener2, times(1)).onSubscribe("dubbo-demo", meshAppRuleListener);
meshRuleManager.register("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
MeshRuleListener meshRuleListener2 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
fail();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type2";
}
};
meshRuleManager.register("dubbo-demo", meshRuleListener2);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
assertEquals(
2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size());
meshRuleManager.unregister("dubbo-demo", meshRuleListener1);
assertEquals(1, meshRuleManager.getAppRuleListeners().size());
assertEquals(
1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size());
meshRuleManager.unregister("dubbo-demo", meshRuleListener2);
assertEquals(0, meshRuleManager.getAppRuleListeners().size());
verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener);
verify(meshEnvListener2, times(1)).onUnSubscribe("dubbo-demo");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRuleSpec;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.Subset;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class MeshRuleCacheTest {
private Invoker<Object> createInvoker(String app) {
URL url = URL.valueOf(
"dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app));
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.getUrl()).thenReturn(url);
return invoker;
}
@Test
void containMapKeyValue() {
URL url = mock(URL.class);
when(url.getOriginalServiceParameter("test", "key1")).thenReturn("value1");
when(url.getOriginalServiceParameter("test", "key2")).thenReturn("value2");
when(url.getOriginalServiceParameter("test", "key3")).thenReturn("value3");
when(url.getOriginalServiceParameter("test", "key4")).thenReturn("value4");
Map<String, String> originMap = new HashMap<>();
originMap.put("key1", "value1");
originMap.put("key2", "value2");
originMap.put("key3", "value3");
Map<String, String> inputMap = new HashMap<>();
inputMap.put("key1", "value1");
inputMap.put("key2", "value2");
assertTrue(MeshRuleCache.isLabelMatch(url, "test", inputMap));
inputMap.put("key4", "value4");
assertTrue(MeshRuleCache.isLabelMatch(url, "test", inputMap));
}
@Test
void testBuild() {
BitList<Invoker<Object>> invokers =
new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1")));
Subset subset = new Subset();
subset.setName("TestSubset");
DestinationRule destinationRule = new DestinationRule();
DestinationRuleSpec destinationRuleSpec = new DestinationRuleSpec();
destinationRuleSpec.setSubsets(Collections.singletonList(subset));
destinationRule.setSpec(destinationRuleSpec);
VsDestinationGroup vsDestinationGroup = new VsDestinationGroup();
vsDestinationGroup.getDestinationRuleList().add(destinationRule);
Map<String, VsDestinationGroup> vsDestinationGroupMap = new HashMap<>();
vsDestinationGroupMap.put("app1", vsDestinationGroup);
MeshRuleCache<Object> cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap);
assertEquals(2, cache.getUnmatchedInvokers().size());
assertEquals(1, cache.getSubsetInvokers("app1", "TestSubset").size());
subset.setLabels(Collections.singletonMap("test", "test"));
cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap);
assertEquals(3, cache.getUnmatchedInvokers().size());
assertEquals(0, cache.getSubsetInvokers("app1", "TestSubset").size());
invokers = new BitList<>(Arrays.asList(
createInvoker(""), createInvoker("unknown"), createInvoker("app1"), createInvoker("app2")));
subset.setLabels(null);
cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap);
assertEquals(3, cache.getUnmatchedInvokers().size());
assertEquals(1, cache.getSubsetInvokers("app1", "TestSubset").size());
assertEquals(0, cache.getSubsetInvokers("app2", "TestSubset").size());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class MeshAppRuleListenerTest {
private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " host: demo\n"
+ " subsets:\n"
+ " - labels: { env-sign: xxx, tag1: hello }\n"
+ " name: isolation\n"
+ " - labels: { env-sign: yyy }\n"
+ " name: testing-trunk\n"
+ " - labels: { env-sign: zzz }\n"
+ " name: testing\n"
+ " trafficPolicy:\n"
+ " loadBalancer: { simple: ROUND_ROBIN }\n"
+ "\n";
private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route }\n"
+ "spec:\n"
+ " dubbo:\n"
+ " - routedetail:\n"
+ " - match:\n"
+ " - sourceLabels: {trafficLabel: xxx}\n"
+ " name: xxx-project\n"
+ " route:\n"
+ " - destination: {host: demo, subset: isolation}\n"
+ " - match:\n"
+ " - sourceLabels: {trafficLabel: testing-trunk}\n"
+ " name: testing-trunk\n"
+ " route:\n"
+ " - destination: {host: demo, subset: testing-trunk}\n"
+ " - name: testing\n"
+ " route:\n"
+ " - destination: {host: demo, subset: testing}\n"
+ " services:\n"
+ " - {regex: ccc}\n"
+ " hosts: [demo]\n";
private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "spec:\n"
+ " host: demo\n"
+ " subsets:\n"
+ " - labels: { env-sign: xxx, tag1: hello }\n"
+ " name: isolation\n"
+ " - labels: { env-sign: yyy }\n"
+ " name: testing-trunk\n"
+ " - labels: { env-sign: zzz }\n"
+ " name: testing\n"
+ " trafficPolicy:\n"
+ " loadBalancer: { simple: ROUND_ROBIN }\n";
private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n";
private static final String rule5 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route.Type1 }\n"
+ "spec:\n"
+ " host: demo\n"
+ "\n";
private static final String rule6 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route.Type1 }\n"
+ "spec:\n"
+ " hosts: [demo]\n";
private static final String rule7 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n"
+ "metadata: { name: demo-route.Type2 }\n"
+ "spec:\n"
+ " host: demo\n"
+ "\n";
private static final String rule8 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n"
+ "metadata: { name: demo-route.Type2 }\n"
+ "spec:\n"
+ " hosts: [demo]\n";
@Test
void testStandard() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter);
meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2);
ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class);
verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
List<Map<String, Object>> rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
Assertions.assertEquals("demo-route", appCaptor.getValue());
meshAppRuleListener.receiveConfigInfo("");
verify(standardMeshRuleRouter, times(1)).clearRule("demo-route");
}
@Test
void register() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter1);
Assertions.assertEquals(
1,
meshAppRuleListener
.getMeshRuleDispatcher()
.getListenerMap()
.get(MeshRuleConstants.STANDARD_ROUTER_KEY)
.size());
meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2);
meshAppRuleListener.register(standardMeshRuleRouter2);
Assertions.assertEquals(
2,
meshAppRuleListener
.getMeshRuleDispatcher()
.getListenerMap()
.get(MeshRuleConstants.STANDARD_ROUTER_KEY)
.size());
ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class);
verify(standardMeshRuleRouter1, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
List<Map<String, Object>> rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
Assertions.assertEquals("demo-route", appCaptor.getValue());
verify(standardMeshRuleRouter2, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
Assertions.assertEquals("demo-route", appCaptor.getValue());
}
@Test
void unregister() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter1);
Assertions.assertEquals(
1,
meshAppRuleListener
.getMeshRuleDispatcher()
.getListenerMap()
.get(MeshRuleConstants.STANDARD_ROUTER_KEY)
.size());
meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2);
meshAppRuleListener.register(standardMeshRuleRouter2);
Assertions.assertEquals(
2,
meshAppRuleListener
.getMeshRuleDispatcher()
.getListenerMap()
.get(MeshRuleConstants.STANDARD_ROUTER_KEY)
.size());
meshAppRuleListener.unregister(standardMeshRuleRouter1);
Assertions.assertEquals(
1,
meshAppRuleListener
.getMeshRuleDispatcher()
.getListenerMap()
.get(MeshRuleConstants.STANDARD_ROUTER_KEY)
.size());
meshAppRuleListener.unregister(standardMeshRuleRouter2);
Assertions.assertEquals(
0, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size());
}
@Test
void process() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter);
ConfigChangedEvent configChangedEvent = new ConfigChangedEvent(
"demo-route" + MESH_RULE_DATA_ID_SUFFIX,
DynamicConfiguration.DEFAULT_GROUP,
rule1 + "---\n" + rule2,
ConfigChangeType.ADDED);
meshAppRuleListener.process(configChangedEvent);
ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class);
verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
List<Map<String, Object>> rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
configChangedEvent = new ConfigChangedEvent(
"demo-route" + MESH_RULE_DATA_ID_SUFFIX,
DynamicConfiguration.DEFAULT_GROUP,
rule1 + "---\n" + rule2,
ConfigChangeType.MODIFIED);
meshAppRuleListener.process(configChangedEvent);
verify(standardMeshRuleRouter, times(2)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
configChangedEvent = new ConfigChangedEvent(
"demo-route" + MESH_RULE_DATA_ID_SUFFIX,
DynamicConfiguration.DEFAULT_GROUP,
"",
ConfigChangeType.DELETED);
meshAppRuleListener.process(configChangedEvent);
verify(standardMeshRuleRouter, times(1)).clearRule("demo-route");
}
@Test
void testUnknownRule() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter);
meshAppRuleListener.receiveConfigInfo(rule3 + "---\n" + rule2);
ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class);
verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
List<Map<String, Object>> rulesReceived = ruleCaptor.getValue();
assertEquals(1, rulesReceived.size());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule4);
verify(standardMeshRuleRouter, times(2)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
rulesReceived = ruleCaptor.getValue();
assertEquals(1, rulesReceived.size());
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
meshAppRuleListener.receiveConfigInfo(rule3 + "---\n" + rule4);
verify(standardMeshRuleRouter, times(1)).clearRule("demo-route");
}
@Test
void testMultipleRule() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
AtomicInteger count = new AtomicInteger(0);
MeshRuleListener listener1 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.assertEquals("demo-route", appName);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rules.contains(yaml.load(rule5)));
Assertions.assertTrue(rules.contains(yaml.load(rule6)));
count.incrementAndGet();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type1";
}
};
MeshRuleListener listener2 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.assertEquals("demo-route", appName);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rules.contains(yaml.load(rule7)));
Assertions.assertTrue(rules.contains(yaml.load(rule8)));
count.incrementAndGet();
}
@Override
public void clearRule(String appName) {}
@Override
public String ruleSuffix() {
return "Type2";
}
};
MeshRuleListener listener4 = new MeshRuleListener() {
@Override
public void onRuleChange(String appName, List<Map<String, Object>> rules) {
Assertions.fail();
}
@Override
public void clearRule(String appName) {
Assertions.assertEquals("demo-route", appName);
count.incrementAndGet();
}
@Override
public String ruleSuffix() {
return "Type4";
}
};
StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter);
meshAppRuleListener.register(listener1);
meshAppRuleListener.register(listener2);
meshAppRuleListener.register(listener4);
meshAppRuleListener.receiveConfigInfo(
rule1 + "---\n" + rule2 + "---\n" + rule5 + "---\n" + rule6 + "---\n" + rule7 + "---\n" + rule8);
ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class);
verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture());
List<Map<String, Object>> rulesReceived = ruleCaptor.getValue();
assertEquals(2, rulesReceived.size());
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1)));
Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2)));
Assertions.assertEquals("demo-route", appCaptor.getValue());
Assertions.assertEquals(3, count.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StandardMeshRuleRouterFactoryTest {
@Test
void getRouter() {
StandardMeshRuleRouterFactory ruleRouterFactory = new StandardMeshRuleRouterFactory();
Assertions.assertTrue(
ruleRouterFactory.getRouter(Object.class, URL.valueOf("")) instanceof StandardMeshRuleRouter);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY;
/**
* Configurator. (SPI, Prototype, ThreadSafe)
*
*/
public interface Configurator extends Comparable<Configurator> {
/**
* Get the configurator url.
*
* @return configurator url.
*/
URL getUrl();
/**
* Configure the provider url.
*
* @param url - old provider url.
* @return new provider url.
*/
URL configure(URL url);
/**
* Convert override urls to map for use when re-refer. Send all rules every time, the urls will be reassembled and
* calculated
*
* URL contract:
* <ol>
* <li>override://0.0.0.0/...( or override://ip:port...?anyhost=true)¶1=value1... means global rules
* (all of the providers take effect)</li>
* <li>override://ip:port...?anyhost=false Special rules (only for a certain provider)</li>
* <li>override:// rule is not supported... ,needs to be calculated by registry itself</li>
* <li>override://0.0.0.0/ without parameters means clearing the override</li>
* </ol>
*
* @param urls URL list to convert
* @return converted configurator list
*/
static Optional<List<Configurator>> toConfigurators(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return Optional.empty();
}
ConfiguratorFactory configuratorFactory = urls.get(0)
.getOrDefaultApplicationModel()
.getExtensionLoader(ConfiguratorFactory.class)
.getAdaptiveExtension();
List<Configurator> configurators = new ArrayList<>(urls.size());
for (URL url : urls) {
if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
configurators.clear();
break;
}
Map<String, String> override = new HashMap<>(url.getParameters());
// The anyhost parameter of override may be added automatically, it can't change the judgement of changing
// url
override.remove(ANYHOST_KEY);
if (CollectionUtils.isEmptyMap(override)) {
continue;
}
configurators.add(configuratorFactory.getConfigurator(url));
}
Collections.sort(configurators);
return Optional.of(configurators);
}
/**
* Sort by host, then by priority
* 1. the url with a specific host ip should have higher priority than 0.0.0.0
* 2. if two url has the same host, compare by priority value;
*/
@Override
default int compareTo(Configurator o) {
if (o == null) {
return -1;
}
int ipCompare = getUrl().getHost().compareTo(o.getUrl().getHost());
// host is the same, sort by priority
if (ipCompare == 0) {
int i = getUrl().getParameter(PRIORITY_KEY, 0);
int j = o.getUrl().getParameter(PRIORITY_KEY, 0);
return Integer.compare(i, j);
} else {
return ipCompare;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.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.rpc.cluster;
import org.apache.dubbo.common.Node;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import java.util.List;
/**
* Directory. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Directory_service">Directory Service</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
*/
public interface Directory<T> extends Node {
/**
* get service type.
*
* @return service type.
*/
Class<T> getInterface();
/**
* list invokers.
* filtered by invocation
*
* @return invokers
*/
List<Invoker<T>> list(Invocation invocation) throws RpcException;
/**
* list invokers
* include all invokers from registry
*/
List<Invoker<T>> getAllInvokers();
URL getConsumerUrl();
boolean isDestroyed();
default boolean isEmpty() {
return CollectionUtils.isEmpty(getAllInvokers());
}
default boolean isServiceDiscovery() {
return false;
}
void discordAddresses();
RouterChain<T> getRouterChain();
/**
* invalidate an invoker, add it into reconnect task, remove from list next time
* will be recovered by address refresh notification or reconnect success notification
*
* @param invoker invoker to invalidate
*/
void addInvalidateInvoker(Invoker<T> invoker);
/**
* disable an invoker, remove from list next time
* will be removed when invoker is removed by address refresh notification
* using in service offline notification
*
* @param invoker invoker to invalidate
*/
void addDisabledInvoker(Invoker<T> invoker);
/**
* recover a disabled invoker
*
* @param invoker invoker to invalidate
*/
void recoverDisabledInvoker(Invoker<T> invoker);
default boolean isNotificationReceived() {
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* RouterFactory. (SPI, Singleton, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
* @see org.apache.dubbo.rpc.cluster.Directory#list(org.apache.dubbo.rpc.Invocation)
* <p>
* Note Router has a different behaviour since 2.7.0, for each type of Router, there will only has one Router instance
* for each service. See {@link CacheableRouterFactory} and {@link RouterChain} for how to extend a new Router or how
* the Router instances are loaded.
*/
@SPI
public interface RouterFactory {
/**
* Create router.
* Since 2.7.0, most of the time, we will not use @Adaptive feature, so it's kept only for compatibility.
*
* @param url url
* @return router instance
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
Router getRouter(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.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.rpc.cluster;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.cluster.merger.MergerFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class MergeableClusterScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(MergerFactory.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import java.util.List;
@SPI
public interface RuleConverter {
List<URL> convert(URL subscribeUrl, Object source);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* ConfiguratorFactory. (SPI, Singleton, ThreadSafe)
*
*/
@SPI
public interface ConfiguratorFactory {
/**
* get the configurator instance.
*
* @param url - configurator url.
* @return configurator instance.
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
Configurator getConfigurator(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;
import java.util.List;
/**
* LoadBalance. (SPI, Singleton, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Load_balancing_(computing)">Load-Balancing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
*/
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {
/**
* select one invoker in list.
*
* @param invokers invokers.
* @param url refer url
* @param invocation invocation.
* @return selected invoker.
*/
@Adaptive("loadbalance")
<T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.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.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterResult;
import java.util.List;
/**
* Router. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory, boolean)
* @see org.apache.dubbo.rpc.cluster.Directory#list(Invocation)
*/
public interface Router extends Comparable<Router> {
int DEFAULT_PRIORITY = Integer.MAX_VALUE;
/**
* Get the router url.
*
* @return url
*/
URL getUrl();
/**
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
*
* @param invokers invoker list
* @param url refer url
* @param invocation invocation
* @return routed invokers
* @throws RpcException
*/
@Deprecated
default <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
return null;
}
/**
* ** This method can return the state of whether routerChain needed to continue route. **
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
*
* @param invokers invoker list
* @param url refer url
* @param invocation invocation
* @param needToPrintMessage whether to print router state. Such as `use router branch a`.
* @return state with route result
* @throws RpcException
*/
default <T> RouterResult<Invoker<T>> route(
List<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage) throws RpcException {
return new RouterResult<>(route(invokers, url, invocation));
}
/**
* Notify the router the invoker list. Invoker list may change from time to time. This method gives the router a
* chance to prepare before {@link Router#route(List, URL, Invocation)} gets called.
*
* @param invokers invoker list
* @param <T> invoker's type
*/
default <T> void notify(List<Invoker<T>> invokers) {}
/**
* To decide whether this router need to execute every time an RPC comes or should only execute when addresses or
* rule change.
*
* @return true if the router need to execute every time.
*/
boolean isRuntime();
/**
* To decide whether this router should take effect when none of the invoker can match the router rule, which
* means the {@link #route(List, URL, Invocation)} would be empty. Most of time, most router implementation would
* default this value to false.
*
* @return true to execute if none of invokers matches the current router
*/
boolean isForce();
/**
* Router's priority, used to sort routers.
*
* @return router's priority
*/
int getPriority();
default void stop() {
// do nothing by default
}
@Override
default int compareTo(Router o) {
if (o == null) {
throw new IllegalArgumentException();
}
return Integer.compare(this.getPriority(), o.getPriority());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.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.rpc.cluster;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class ClusterScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(RouterSnapshotSwitcher.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(ClusterUtils.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.