src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
ParseConfigUtils { private Map<String, Object> mergeDimensionItems(Map<String, Map<String, Object>> items) { Map<String, Object> flatMap = new HashMap<>(); Set<String> keySet = items.keySet(); if (keySet.contains("application")) { flatMap.putAll(items.get("application")); keySet.remove("application"); } if (!keySet.isE... | @Test public void testMergeDimensionItems() { boolean status = true; Map<String, Object> application = new HashMap<>(); application.put("key1", "application1"); application.put("key2", "application2"); application.put("key3", "application3"); application.put("key4", "application4"); Map<String, Object> service = new Ha... |
MemberDiscovery { public String getConfigServer() { synchronized (lock) { if (configServerAddresses.isEmpty()) { throw new IllegalStateException("Config center address is not available."); } int index = Math.abs(counter.get() % configServerAddresses.size()); return configServerAddresses.get(index); } } MemberDiscovery(... | @Test public void testGetConfigServerURIs() { MemberDiscovery dc = new MemberDiscovery(ConfigCenterConfig.INSTANCE.getServerUri()); assertNotNull(dc.getConfigServer()); } |
ConfigCenterConfig { public List<String> getServerUri() { return Deployment.getSystemBootStrapInfo(DeploymentProvider.SYSTEM_KEY_CONFIG_CENTER).getAccessURL(); } private ConfigCenterConfig(); static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config); static ConcurrentCompositeConfigurati... | @Test public void getServerUri() { List<String> servers = ConfigCenterConfig.INSTANCE.getServerUri(); Assert.assertEquals("https: Assert.assertEquals("https: } |
ZeroConfigRegistryService { public void heartbeat(ServerMicroserviceInstance receivedInstance) { String serviceId = receivedInstance.getServiceId(); String instanceId = receivedInstance.getInstanceId(); Map<String, ServerMicroserviceInstance> serverMicroserviceInstanceMap = ServerUtil.microserviceInstanceMap .get(servi... | @Test public void test_heartbeat_whenInstanceExist_shouldReturnTrue() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(false); boolean returnedResult = target.heartbeat(serviceId, instanceId); Assert.assertTrue(returnedResult); }
@Test public void test_heartbeat_whenInstanceNotExist_shouldReturnFalse() ... |
ConfigCenterConfig { public String getEnvironment() { return BootStrapProperties.readServiceEnvironment(finalConfig); } private ConfigCenterConfig(); static void setConcurrentCompositeConfiguration(ConcurrentCompositeConfiguration config); static ConcurrentCompositeConfiguration getConcurrentCompositeConfiguration(); ... | @Test public void getEnvironment() { Assert.assertEquals("testing", ConfigCenterConfig.INSTANCE.getEnvironment()); System.setProperty("SERVICECOMB_ENV", "development"); ConfigCenterConfig.setConcurrentCompositeConfiguration(ConfigUtil.createLocalConfig()); Assert.assertEquals("development", ConfigCenterConfig.INSTANCE.... |
NacosConfigurationSourceImpl implements ConfigCenterConfigurationSource { @Override public void addUpdateListener(WatchedUpdateListener watchedUpdateListener) { listeners.add(watchedUpdateListener); } NacosConfigurationSourceImpl(); @Override boolean isValidSource(Configuration localConfiguration); @Override void init(... | @Test public void testCreate() throws Exception { NacosConfigurationSourceImpl nacosConfigurationSource = new NacosConfigurationSourceImpl(); nacosConfigurationSource.addUpdateListener(result -> Assert.assertTrue(!result.getAdded().isEmpty())); UpdateHandler udateHandler = Deencapsulation.getField(nacosConfigurationSou... |
NacosConfigurationSourceImpl implements ConfigCenterConfigurationSource { @Override public void removeUpdateListener(WatchedUpdateListener watchedUpdateListener) { listeners.remove(watchedUpdateListener); } NacosConfigurationSourceImpl(); @Override boolean isValidSource(Configuration localConfiguration); @Override void... | @Test public void testRemoveUpdateListener() { NacosConfigurationSourceImpl nacosConfigurationSource = new NacosConfigurationSourceImpl(); WatchedUpdateListener watchedUpdateListener = Mockito.mock(WatchedUpdateListener.class); nacosConfigurationSource.addUpdateListener(watchedUpdateListener); nacosConfigurationSource.... |
NacosClient { public void refreshNacosConfig() { new ConfigRefresh().refreshConfig(); } NacosClient(UpdateHandler updateHandler); void refreshNacosConfig(); } | @Test public void refreshNacosConfig() { NacosConfigurationSourceImpl impl = new NacosConfigurationSourceImpl(); UpdateHandler updateHandler = impl.new UpdateHandler(); NacosClient nacosClient = new NacosClient(updateHandler); Map<String, Object> originMap = Deencapsulation.getField(nacosClient, "originalConfigMap"); o... |
KieUtil { public static Map<String, Object> processValueType(KVDoc kvDoc) { ValueType valueType = parseValueType(kvDoc.getValueType()); if (valueType == (ValueType.YAML) || valueType == (ValueType.YML)) { return Parser.findParser(Parser.CONTENT_TYPE_YAML).parse(kvDoc.getValue(), kvDoc.getKey(), true); } else if (valueT... | @Test public void test_processValueType() { KVDoc kvDoc = new KVDoc(); kvDoc.setKey("hello"); kvDoc.setValue("world"); Map<String, Object> result = KieUtil.processValueType(kvDoc); Assert.assertEquals("world", result.get("hello")); kvDoc.setValueType("text"); result = KieUtil.processValueType(kvDoc); Assert.assertEqual... |
KieClient { public void refreshKieConfig() { if (enableLongPolling) { EXECUTOR.execute(new ConfigRefresh(serviceUri)); } else { EXECUTOR.scheduleWithFixedDelay(new ConfigRefresh(serviceUri), firstRefreshInterval, refreshInterval, TimeUnit.MILLISECONDS); } } KieClient(UpdateHandler updateHandler); void refreshKieConfig(... | @SuppressWarnings("unchecked") @Test public void testRefreshKieConfig() { HttpClientRequest request = Mockito.mock(HttpClientRequest.class); Mockito.when(request.method()).thenReturn(HttpMethod.GET); Mockito.when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap()); Buffer rsp = Mockito.mock(Buffer.class);... |
KieClient { public void destroy() { if (EXECUTOR != null) { EXECUTOR.shutdown(); EXECUTOR = null; } } KieClient(UpdateHandler updateHandler); void refreshKieConfig(); void destroy(); } | @Test public void destroy() { KieClient kieClient = new KieClient(null); ScheduledExecutorService executor = Deencapsulation.getField(kieClient, "EXECUTOR"); Assert.assertFalse(executor.isShutdown()); executor.shutdown(); Assert.assertTrue(executor.isShutdown()); } |
KieConfig { public String getServerUri() { return finalConfig.getString(SERVER_URL_KEY); } private KieConfig(); static ConcurrentCompositeConfiguration getFinalConfig(); static void setFinalConfig(ConcurrentCompositeConfiguration finalConfig); int getConnectionTimeOut(); int getEventLoopSize(); int getVerticalInstance... | @Test public void getServerUri() { String servers = KieConfig.INSTANCE.getServerUri(); Assert.assertEquals("https: } |
KieConfig { public String getEnvironment() { return BootStrapProperties.readServiceEnvironment(finalConfig); } private KieConfig(); static ConcurrentCompositeConfiguration getFinalConfig(); static void setFinalConfig(ConcurrentCompositeConfiguration finalConfig); int getConnectionTimeOut(); int getEventLoopSize(); int... | @Test public void getEnvironment() { Assert.assertEquals("testing", KieConfig.INSTANCE.getEnvironment()); System.setProperty("SERVICECOMB_ENV", "development"); KieConfig.setFinalConfig(ConfigUtil.createLocalConfig()); Assert.assertEquals("development", KieConfig.INSTANCE.getEnvironment()); } |
KieWatcher { public void refreshConfigItems(Map<String, Object> remoteItems) { String md5Vaule = KieUtil.encrypt(remoteItems.toString()); if (CollectionUtils.isEmpty(remoteItems)) { updateHandler.handle("delete", lastTimeData); lastTimeData = remoteItems; return; } if (StringUtils.isEmpty(refreshRecord)) { refreshRecor... | @Test public void testRefreshConfigItems() { boolean status = true; Map<String, Object> configMap = new HashMap<>(); configMap.put("key1", "application1"); configMap.put("key2", "application2"); configMap.put("key3", "application3"); configMap.put("key4", "application4"); Map<String, Object> result = null; try { result... |
ZeroConfigRegistryService { public ServerMicroserviceInstance getMicroservice(String microserviceId) { Map<String, ServerMicroserviceInstance> instanceIdMap = ServerUtil.microserviceInstanceMap .get(microserviceId); if (instanceIdMap != null) { List<ServerMicroserviceInstance> serverMicroserviceInstanceList = new Array... | @Test public void test_getMicroservice_whenServiceExist_shouldReturnService() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); ServerMicroserviceInstance returnedResult = target.getMicroservice(serviceId); Assert.assertNotNull(returnedResult); Assert.assertEquals(serviceId, returnedResult.getServ... |
ZeroConfigRegistryService { public List<ServerMicroserviceInstance> findServiceInstances(String appId, String serviceName) { List<ServerMicroserviceInstance> resultInstanceList = new ArrayList<>(); ServerUtil.microserviceInstanceMap.forEach((serviceId, instanceIdMap) -> { instanceIdMap.forEach((instanceId, instance) ->... | @Test public void test_findServiceInstances_whenInstanceExist_shouldReturnInstanceList() { ServerUtil.microserviceInstanceMap = prepareServiceInstanceMap(true); List<ServerMicroserviceInstance> returnedResult = target .findServiceInstances(appId, serviceName); Assert.assertTrue(!returnedResult.isEmpty()); Assert.assert... |
LoadbalanceExceptionUtils extends ExceptionUtils { public static CseException createLoadbalanceException(String code, Throwable cause, Object... args) { String msg = String.format(ERROR_DESC_MGR.ensureFindValue(code), args); CseException exception = new CseException(code, msg, cause); return exception; } static CseExc... | @Test public void testLoadbalanceExceptionUtils() { assertEquals("servicecomb.handler.lb.wrong.rule", LoadbalanceExceptionUtils.CSE_HANDLER_LB_WRONG_RULE); CseException cseException = LoadbalanceExceptionUtils.createLoadbalanceException("servicecomb.handler.lb.wrong.rule", new Throwable(), "ARGS"); Assert.assertNotNull... |
IsolationDiscoveryFilter implements DiscoveryFilter { @Override public DiscoveryTreeNode discovery(DiscoveryContext context, DiscoveryTreeNode parent) { Map<String, MicroserviceInstance> instances = parent.data(); Invocation invocation = context.getInputParameters(); if (!Configuration.INSTANCE.isIsolationFilterOpen(in... | @Test public void discovery_no_instance_reach_error_threshold() { DiscoveryTreeNode childNode = filter.discovery(discoveryContext, discoveryTreeNode); Map<String, MicroserviceInstance> childNodeData = childNode.data(); Assert.assertThat(childNodeData.keySet(), Matchers.containsInAnyOrder("i0", "i1", "i2")); Assert.asse... |
InstancePropertyDiscoveryFilter extends AbstractDiscoveryFilter { protected boolean allowVisit(MicroserviceInstance instance, Map<String, String> filterOptions) { Map<String, String> propertiesMap = instance.getProperties(); for (Entry<String, String> entry : filterOptions.entrySet()) { if (!entry.getValue().equals(pro... | @Test public void testAllowVisit() { Map<String, String> filterOptions = new HashMap<>(); Assert.assertTrue(filter.allowVisit(instance, filterOptions)); filterOptions.put("tag0", "value0"); Assert.assertTrue(filter.allowVisit(instance, filterOptions)); filterOptions.put("tag2", "value2"); Assert.assertFalse(filter.allo... |
ServerDiscoveryFilter extends EndpointDiscoveryFilter { @Override protected Object createEndpoint(String transportName, String endpoint, MicroserviceInstance instance) { Transport transport = SCBEngine.getInstance().getTransportManager().findTransport(transportName); if (transport == null) { LOGGER.info("not deployed t... | @Test public void createEndpoint_TransportNotExist() { new Expectations(transportManager) { { transportManager.findTransport(anyString); result = null; } }; ServiceCombServer server = (ServiceCombServer) filter.createEndpoint(Const.RESTFUL, null, null); Assert.assertNull(server); }
@Test public void createEndpointNorma... |
Configuration { public int getRetryNextServer(String microservice) { return getRetryServer(microservice, RETRY_ON_NEXT); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHan... | @Test public void testConfigurationWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.getRetryNextServer("test"); assertNotNull(Configuration.INSTANCE.getRetryNextServer("test")); }
@Test pu... |
Configuration { public int getRetrySameServer(String microservice) { return getRetryServer(microservice, RETRY_ON_SAME); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String microservice); int getSuccessiveFailedTimes(String microservice); String getRetryHan... | @Test public void testGetRetryOnSameWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.getRetrySameServer("test"); assertNotNull(Configuration.INSTANCE.getRetrySameServer("test")); }
@Test p... |
Configuration { public boolean isRetryEnabled(String microservice) { String p = getStringProperty("false", ROOT + microservice + "." + RETRY_ENABLED, ROOT + RETRY_ENABLED); return Boolean.parseBoolean(p); } private Configuration(); String getRuleStrategyName(String microservice); int getSessionTimeoutInSeconds(String ... | @Test public void testIsRetryEnabledWithGetpropertyReturnsStringChar() { new MockUp<Configuration>() { @Mock private String getProperty(String defaultValue, String... keys) { return "tyt"; } }; Configuration.INSTANCE.isRetryEnabled("test"); assertNotNull(Configuration.INSTANCE.isRetryEnabled("test")); }
@Test public vo... |
Configuration { public int getSuccessiveFailedTimes(String microservice) { final int defaultValue = 5; String p = getStringProperty("5", ROOT + microservice + "." + SUCCESSIVE_FAILED_TIMES, ROOT + SUCCESSIVE_FAILED_TIMES); try { return Integer.parseInt(p); } catch (NumberFormatException e) { return defaultValue; } } pr... | @Test public void testGetSuccessiveFailedTimes() { assertNotNull(Configuration.INSTANCE.getSuccessiveFailedTimes("test")); } |
Configuration { public int getSessionTimeoutInSeconds(String microservice) { final int defaultValue = 30; String p = getStringProperty("30", ROOT + microservice + "." + SESSION_TIMEOUT_IN_SECONDS, ROOT + SESSION_TIMEOUT_IN_SECONDS); try { return Integer.parseInt(p); } catch (NumberFormatException e) { return defaultVal... | @Test public void testGetSessionTimeoutInSeconds() { assertNotNull(Configuration.INSTANCE.getSessionTimeoutInSeconds("test")); } |
Configuration { public int getMaxSingleTestWindow() { final int defaultValue = 60000; String p = getStringProperty(Integer.toString(defaultValue), ROOT + FILTER_ISOLATION + FILTER_MAX_SINGLE_TEST_WINDOW); try { int result = Integer.parseInt(p); if (result >= 0) { return result; } return defaultValue; } catch (NumberFor... | @Test public void testGetMaxSingleTestWindow() { assertEquals(60000, Configuration.INSTANCE.getMaxSingleTestWindow()); ArchaiusUtils.setProperty("servicecomb.loadbalance.isolation.maxSingleTestWindow", 5000); assertEquals(5000, Configuration.INSTANCE.getMaxSingleTestWindow()); } |
LoadbalanceHandler implements Handler { private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, LoadBalancer chosenLB) throws Exception { long time = System.currentTimeMillis(); int currentHandler = invocation.getHandlerIndex(); SyncResponseExecutor orginExecutor; Executor newExecutor; if (invocation... | @Test public void sendWithRetry(@Injectable LoadBalancer loadBalancer) { Holder<String> result = new Holder<>(); Deencapsulation.invoke(handler, "sendWithRetry", invocation, (AsyncResponse) resp -> { result.value = resp.getResult(); }, loadBalancer); } |
LoadbalanceHandler implements Handler { protected boolean isFailedResponse(Response resp) { if (resp.isFailed()) { if (InvocationException.class.isInstance(resp.getResult())) { InvocationException e = (InvocationException) resp.getResult(); return e.getStatusCode() == ExceptionFactory.CONSUMER_INNER_STATUS_CODE || e.ge... | @Test public void testIsFailedResponse() { Assert.assertFalse(handler.isFailedResponse(Response.create(400, "", ""))); Assert.assertFalse(handler.isFailedResponse(Response.create(500, "", ""))); Assert.assertTrue(handler.isFailedResponse(Response.create(490, "", ""))); Assert.assertTrue(handler.isFailedResponse(Respons... |
ExtensionsManager { public static RuleExt createLoadBalancerRule(String microservice) { RuleExt rule = null; for (ExtensionsFactory factory : extentionFactories) { if (factory.isSupport(Configuration.RULE_STRATEGY_NAME, Configuration.INSTANCE.getRuleStrategyName(microservice))) { rule = factory.createLoadBalancerRule( ... | @Test public void testRuleName() { System.setProperty("servicecomb.loadbalance.mytest1.strategy.name", "RoundRobin"); System.setProperty("servicecomb.loadbalance.mytest2.strategy.name", "Random"); System.setProperty("servicecomb.loadbalance.mytest3.strategy.name", "WeightedResponse"); System.setProperty("servicecomb.lo... |
ExtensionsManager { public static RetryHandler createRetryHandler(String microservice) { RetryHandler handler = null; for (ExtensionsFactory factory : extentionFactories) { if (factory.isSupport(Configuration.RETRY_HANDLER, Configuration.INSTANCE.getRetryHandler(microservice))) { handler = factory.createRetryHandler(Co... | @Test public void testRuleClassName() { BeansHolder holder = new BeansHolder(); List<ExtensionsFactory> extensionsFactories = new ArrayList<>(); extensionsFactories.add(new RuleNameExtentionsFactory()); extensionsFactories.add(new DefaultRetryExtensionsFactory()); Deencapsulation.setField(holder, "extentionsFactories",... |
RoundRobinRuleExt implements RuleExt { @Override public ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation) { if (servers.isEmpty()) { return null; } int index = Math.abs(counter.getAndIncrement()) % servers.size(); return servers.get(index); } @Override ServiceCombServer choose(List<Servi... | @Test public void testRoundRobin() { RoundRobinRuleExt rule = new RoundRobinRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 2; i++) { ServiceCombServer server = ... |
WeightedResponseTimeRuleExt extends RoundRobinRuleExt { @Override public ServiceCombServer choose(List<ServiceCombServer> servers, Invocation invocation) { List<Double> stats = calculateTotalWeights(servers); if (stats.size() > 0) { double finalTotal = stats.get(stats.size() - 1); List<Double> weights = new ArrayList<>... | @Test public void testRoundRobin() { WeightedResponseTimeRuleExt rule = new WeightedResponseTimeRuleExt(); LoadBalancer loadBalancer = new LoadBalancer(rule, "testService"); List<ServiceCombServer> servers = new ArrayList<>(); Invocation invocation = Mockito.mock(Invocation.class); for (int i = 0; i < 2; i++) { Service... |
ServiceCombServerStats { public static boolean applyForTryingChance(Invocation invocation) { TryingIsolatedServerMarker marker = globalAllowIsolatedServerTryingFlag.get(); if (marker == null) { return globalAllowIsolatedServerTryingFlag.compareAndSet(null, new TryingIsolatedServerMarker(invocation)); } if (marker.isOut... | @Test public void testGlobalAllowIsolatedServerTryingFlag_apply_with_null_precondition() { Invocation invocation = new Invocation(); Assert.assertTrue(ServiceCombServerStats.applyForTryingChance(invocation)); Assert.assertSame(invocation, ServiceCombServerStats.globalAllowIsolatedServerTryingFlag.get().getInvocation())... |
ServiceCombServer extends Server { public Endpoint getEndpoint() { return endpoint; } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString... | @Test public void testGetEndpoint() { cs.getEndpoint(); assertNotNull(cs.getEndpoint()); } |
ServiceCombServer extends Server { public boolean equals(Object o) { if (o instanceof ServiceCombServer) { return this.instance.getInstanceId().equals(((ServiceCombServer) o).instance.getInstanceId()); } else { return false; } } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); S... | @Test public void testEqualsMethod() { Assert.assertFalse(cs.equals((Object) "abcd")); MicroserviceInstance instance1 = new MicroserviceInstance(); instance1.setInstanceId("1234"); ServiceCombServer other = new ServiceCombServer(transport, new CacheEndpoint("1234", instance1)); Assert.assertFalse(cs.equals(other)); Mic... |
ServiceCombServer extends Server { public String toString() { return endpoint.getEndpoint(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String... | @Test public void testToStringMethod() { cs.toString(); assertNotNull(cs.toString()); } |
ServiceCombServer extends Server { public String getHost() { return endpoint.getEndpoint(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String ... | @Test public void testGetHost() { cs.getHost(); assertNotNull(cs.getHost()); } |
ServiceCombServer extends Server { public int hashCode() { return this.instance.getInstanceId().hashCode(); } @VisibleForTesting ServiceCombServer(Endpoint endpoint, MicroserviceInstance instance); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getIns... | @Test public void testHashCodeMethod() { cs.hashCode(); assertNotNull(cs.hashCode()); } |
ProviderQpsFlowControlHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { if (invocation.getHandlerIndex() > 0) { invocation.next(asyncResp); return; } if (!Config.INSTANCE.isProviderEnabled()) { return; } String microserviceName = invocation.getC... | @Test public void testGlobalQpsControl(final @Injectable Invocation invocation, final @Injectable AsyncResponse asyncResp) throws Exception { new Expectations() { { invocation.getHandlerIndex(); result = 0; invocation.getContext(Const.SRC_MICROSERVICE); result = "test"; invocation.getOperationMeta(); result = QpsContro... |
ProviderQpsFlowControlHandler implements Handler { private boolean isLimitNewRequest(QpsStrategy qpsStrategy, AsyncResponse asyncResp) { if (qpsStrategy.isLimitNewRequest()) { CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol"); asyncResp.producerFail(new InvocationException(QpsConst.... | @Test public void testQpsController() { AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("abc"); qpsStrategy.setQpsLimit(100L); assertFalse(qpsStrategy.isLimitNewRequest()); qpsStrategy.setQpsLimit(1L); assertTrue(qpsStrategy.isLimitNewRequest()); } |
OperationPerfGroup { public void addOperationPerf(OperationPerf operationPerf) { operationPerfs.add(operationPerf); if (summary == null) { summary = new OperationPerf(); summary.setOperation(""); } summary.add(operationPerf); } OperationPerfGroup(String transport, String status); String getTransport(); String getStatus... | @Test public void addOperationPerf() { OperationPerf opPerf = Utils.createOperationPerf(op); group.addOperationPerf(opPerf); group.addOperationPerf(opPerf); Assert.assertThat(group.getOperationPerfs(), Matchers.contains(opPerf, opPerf)); OperationPerf summary = group.getSummary(); PerfInfo perfInfo = summary.findStage(... |
QpsControllerManager { public QpsStrategy getOrCreate(String microserviceName, Invocation invocation) { return qualifiedNameControllerMap .computeIfAbsent( microserviceName + SEPARATOR + invocation.getOperationMeta().getSchemaQualifiedName(), key -> create(key, microserviceName, invocation)); } QpsStrategy getOrCreate... | @Test public void testGetOrCreate(@Mocked Invocation invocation, @Mocked OperationMeta operationMeta) { new Expectations() { { invocation.getOperationMeta(); result = operationMeta; invocation.getSchemaId(); result = "server"; operationMeta.getSchemaQualifiedName(); result = "server.test"; } }; QpsControllerManager tes... |
ConsumerQpsFlowControlHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { if (!Config.INSTANCE.isConsumerEnabled()) { invocation.next(asyncResp); return; } QpsStrategy qpsStrategy = qpsControllerMgr.getOrCreate(invocation.getMicroserviceName(), in... | @Test public void testHandle() throws Exception { String key = "svc.schema.opr"; AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("key"); qpsStrategy.setQpsLimit(12L); Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta); Mockito.when(operationMeta.getSchemaQualifiedName(... |
DelayFault extends AbstractFault { @Override public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse) { if (!shouldDelay(invocation, faultParam, asynResponse)) { asynResponse.success(SUCCESS_RESPONSE); return; } LOGGER.debug("Fault injection: delay is added for the request by fa... | @Test public void injectFaultVertxDelay() throws InterruptedException { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.fixedDelay", "10"); ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.delay.percent", "100"); assert... |
PerfInfo { @Override public String toString() { return "PerfInfo [tps=" + tps + ", msTotalTime=" + msTotalTime + ", msLatency=" + calcMsLatency() + ", msMaxLatency=" + msMaxLatency + "]"; } double getTps(); void setTps(double tps); double getMsTotalTime(); void setMsTotalTime(double msTotalTime); double getMsMaxLatenc... | @Test public void testToString() { PerfInfo perf = new PerfInfo(); perf.setTps(10); perf.setMsTotalTime(10); perf.setMsMaxLatency(100); Assert.assertEquals("PerfInfo [tps=10.0, msTotalTime=10.0, msLatency=1.0, msMaxLatency=100.0]", perf.toString()); } |
AbortFault extends AbstractFault { @Override public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asyncResponse) { if (!shouldAbort(invocation, faultParam)) { asyncResponse.success(SUCCESS_RESPONSE); return; } int errorCode = FaultInjectionUtil.getFaultInjectionConfig(invocation, "abort.h... | @Test public void injectFaultError() { ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.httpStatus", "421"); ArchaiusUtils .setProperty("servicecomb.governance.Consumer._global.policy.fault.protocols.rest.abort.percent", "100"); assertEquals("421", DynamicProperty .g... |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected Observable<Response> resumeWithFallback() { Throwable cause = getFailedExecutionException(); Observable<Response> observable = Observable.create(f -> { try { f.onNext(FallbackPolicyManager.getFallbackResponse(type, cause, invocation)); f.... | @Test public void testResumeWithFallbackProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties... |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected Observable<Response> construct() { Observable<Response> observable = Observable.create(f -> { try { invocation.next(resp -> { if (isFailedResponse(resp)) { LOG.warn("bizkeeper command {} failed due to {}", invocation.getInvocationQualifie... | @Test public void testConstructProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter s... |
BizkeeperCommand extends HystrixObservableCommand<Response> { @Override protected String getCacheKey() { if (HystrixRequestContext.isCurrentThreadInitialized()) { StringBuilder sb = new StringBuilder(); sb.append(this.getCommandGroup().name()); sb.append("-"); sb.append(this.getCommandKey().name()); return sb.toString(... | @Test public void testGetCacheKeyWithContextInitializedProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCo... |
OperationPerf { public void add(OperationPerf operationPerf) { operationPerf.stages.forEach((key, value) -> { PerfInfo perfInfo = stages.computeIfAbsent(key, n -> new PerfInfo()); perfInfo.add(value); }); if (operationPerf.getLatencyDistribution() == null) { return; } if (latencyDistribution == null) { latencyDistribut... | @Test public void add() { Assert.assertTrue(opPerf.getStages().isEmpty()); OperationPerf otherOpPerf = Utils.createOperationPerf(op); opPerf.add(otherOpPerf); Assert.assertEquals(op, otherOpPerf.getOperation()); PerfInfo perfInfo = opPerf.findStage(MeterInvocationConst.STAGE_TOTAL); Assert.assertEquals(10, perfInfo.get... |
CommandKey { public static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation) { return CustomizeCommandGroupKey.asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName(), invocation); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(S... | @Test public void testToHystrixCommandGroupKey() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); Assert.assertNotNull(invoc... |
CommandKey { public static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation) { return HystrixCommandKey.Factory .asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName()); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocati... | @Test public void testToHystrixCommandKey() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); Assert.assertNotNull(invocation... |
ConsumerBizkeeperHandler extends BizkeeperHandler { @Override protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) { HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); setCommonProperties(invocation, setter); Bizke... | @Test public void testCreateBizkeeperCommand() { HystrixPlugins.reset(); ConsumerBizkeeperHandler consumerBizkeeperHandler = new ConsumerBizkeeperHandler(); Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(inv... |
BizkeeperRequestContext { public static BizkeeperRequestContext initializeContext() { return new BizkeeperRequestContext(HystrixRequestContext.initializeContext()); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); } | @Test public void testInitializeContext() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); Assert.assertNotNull(bizkeeperRequestContext); } |
BizkeeperRequestContext { public void shutdown() { this.context.shutdown(); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); } | @Test public void testShutdown() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); boolean validAssert; try { bizkeeperRequestContext.shutdown(); validAssert = true; } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); } |
BizkeeperHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) { HystrixObservable<Response> command = delegate.createBizkeeperCommand(invocation); Observable<Response> observable = command.toObservable(); observable.subscribe(asyncResp::complete, error -> { LOG.warn(... | @Test public void testHandleWithException() { boolean validAssert; HystrixPlugins.reset(); try { validAssert = true; bizkeeperHandler.handle(invocation, asyncResp); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
@Test public void testHandle() { boolean validAssert; try { Assert.assert... |
BizkeeperHandler implements Handler { protected void setCommonProperties(Invocation invocation, HystrixCommandProperties.Setter setter) { } BizkeeperHandler(String groupname); @Override void handle(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testSetCommonProperties() { boolean validAssert; try { validAssert = true; HystrixPlugins.reset(); HystrixCommandProperties.Setter setter = Mockito.mock(HystrixCommandProperties.Setter.class); bizkeeperHandler.setCommonProperties(invocation, setter); } catch (Exception e) { validAssert = false; } Asse... |
DefaultLogPublisher implements MetricsInitializer { @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { if (!DynamicPropertyFactory.getInstance() .getBooleanProperty(ENABLED, false) .get()) { return; } initLatencyDistribution(); eventBus.register(this); } @Over... | @Test public void init_enabled_default() { Holder<Boolean> registered = new Holder<>(false); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertFalse(registered.value); }
@Test public vo... |
Configuration { private Configuration() { } private Configuration(); int getIsolationTimeoutInMilliseconds(String type, String microserviceName,
String qualifiedOperationName); boolean getIsolationTimeoutEnabled(String type, String microserviceName,
String qualifiedOperationName); int getIsolationMaxConcur... | @Test public void testConfiguration() { assertNotNull(Configuration.INSTANCE); assertEquals("returnnull", Configuration.FALLBACKPOLICY_POLICY_RETURN); assertEquals("throwexception", Configuration.FALLBACKPOLICY_POLICY_THROW); Configuration c = Configuration.INSTANCE; Invocation invocation = Mockito.mock(Invocation.clas... |
BizkeeperExceptionUtils extends ExceptionUtils { public static CseException createBizkeeperException(String code, Throwable cause, Object... args) { String msg = String.format(ERROR_DESC_MGR.ensureFindValue(code), args); return new CseException(code, msg, cause); } private BizkeeperExceptionUtils(); static CseExceptio... | @Test public void testCreateBizkeeperException() { Assert.assertEquals("servicecomb.bizkeeper.fallback", BizkeeperExceptionUtils.SERVICECOMB_BIZKEEPER_FALLBACK); CseException cseException = BizkeeperExceptionUtils.createBizkeeperException("servicecomb.bizkeeper.fallback", new Throwable(), "ARGS"); Assert.assertNotNull(... |
HystrixPropertiesStrategyExt extends HystrixPropertiesStrategy { public static HystrixPropertiesStrategyExt getInstance() { return INSTANCE; } private HystrixPropertiesStrategyExt(); static HystrixPropertiesStrategyExt getInstance(); @Override HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey,... | @Test public void testGetCommandPropertiesCacheKey() { assertNotNull(HystrixPropertiesStrategyExt.getInstance()); HystrixPropertiesStrategyExt hps = HystrixPropertiesStrategyExt.getInstance(); HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class); Invocation invocation = Mockito.mock(Invocation.class); M... |
HystrixPropertiesStrategyExt extends HystrixPropertiesStrategy { @Override public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder) { HystrixCommandProperties commandProperties = commandPropertiesMap.get(commandKey.name()); if (commandProperties == null) { commandProperties = n... | @Test public void testgetCommandProperties() { HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class); Mockito.when(commandKey.name()) .thenReturn("provider.HystrixPropertiesStrategyExtTest.testgetCommandProperties"); HystrixCommandProperties commandPro = HystrixPropertiesStrategyExt.getInstance() .getCom... |
CircutBreakerEventNotifier extends HystrixEventNotifier { @Override public void markEvent(HystrixEventType eventType, HystrixCommandKey key) { String keyName = key.name(); AtomicBoolean flag = circuitFlag.computeIfAbsent(keyName, k -> new AtomicBoolean()); switch (eventType) { case SHORT_CIRCUITED: if (flag.compareAndS... | @Test public void testMarkEvent() { Mockito.when(commandKey.name()).thenReturn("Consumer.springmvc.springmvcHello.sayHi"); new Expectations(HystrixCommandMetrics.class) { { HystrixCommandMetrics.getInstance(commandKey); result = null; } }; circutBreakerEventNotifier.markEvent(HystrixEventType.SHORT_CIRCUITED, commandKe... |
RSAAuthenticationToken { public RSAAuthenticationToken(String instanceId, String serviceId, long generateTime, String randomCode, String sign) { this.instanceId = instanceId; this.generateTime = generateTime; this.randomCode = randomCode; this.serviceId = serviceId; this.sign = sign; this.tokenFormat = String.format("%... | @Test public void testRSAAuthenticationToken() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException { String tokenstr = "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwP... |
RSAAuthenticationToken { public static RSAAuthenticationToken fromStr(String token) { String[] tokenArr = token.split("@"); if (tokenArr.length != 5) { return null; } return new RSAAuthenticationToken(tokenArr[0], tokenArr[1], Long.valueOf(tokenArr[2]), tokenArr[3], tokenArr[4]); } RSAAuthenticationToken(String instanc... | @Test public void testRSAAuthenticationTokenError() { String tokenstr = "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9... |
DtmProviderHandler implements Handler { @Override public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception { try { if (dtmContextImMethod != null) { String traceId = invocation.getContext().get(Const.TRACE_ID_NAME); invocation.getContext().put(DTM_TRACE_ID_KEY, traceId); dtmContextImMethod.in... | @Test public void testHandler(@Mocked Invocation invocation) throws Exception { DtmProviderHandler providerHandler = new DtmProviderHandler(); providerHandler.init(null, null); Map<String, String> context = new HashMap<>(); new Expectations() {{ invocation.getContext(); result = context; }}; String expectTxId = "dtm-tx... |
CasEnvConfig { public Map<String, String> getNonEmptyProperties() { return properties.entrySet().stream().filter(entry -> StringUtils.isNotEmpty(entry.getValue())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); } private CasEnvConfig(); Map<String, String> getNonEmptyProperties(); static final CasEnvConfi... | @Test public void testConfig() { CasEnvConfig instance = CasEnvConfig.INSTANCE; assertEquals(2, instance.getNonEmptyProperties().size()); assertEquals("application-id", instance.getNonEmptyProperties().get("CAS_APPLICATION_ID")); assertEquals("env-id", instance.getNonEmptyProperties().get("CAS_ENVIRONMENT_ID")); } |
KieClient { public String putKeyValue(String key, KVBody kvBody) { try { ObjectMapper mapper = new ObjectMapper(); HttpResponse response = httpClient.putHttpRequest("/kie/kv/" + key, null, mapper.writeValueAsString(kvBody)); if (response.getStatusCode() == HttpStatus.SC_OK) { return response.getContent(); } else { LOGG... | @Test public void putKeyValue() throws IOException { KieRawClient kieRawClient = Mockito.mock(KieRawClient.class); KVBody kvBody = new KVBody(); kvBody.setValue("test"); kvBody.setValueType("string"); Map<String, String> labels = new HashMap<>(); labels.put("app1", "111"); kvBody.setLabels(labels); HttpResponse httpRes... |
KieClient { public void deleteKeyValue(KVDoc kvDoc) { try { HttpResponse response = httpClient.deleteHttpRequest("/kie/kv/?kvID=" + kvDoc.getId(), null, null); if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) { LOGGER.info("Delete keyValue success"); } else { LOGGER.error("delete keyValue fails, responseStatus... | @Test public void deleteKeyValue() throws IOException { KieRawClient kieRawClient = Mockito.mock(KieRawClient.class); KVDoc kvDoc = new KVDoc(); kvDoc.setId("111"); kvDoc.setKey("test"); kvDoc.setValue("testValue"); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(204); httpResponse.setMessage... |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstancesResponse getServiceCenterInstances() { try { HttpResponse response = httpClient.getHttpRequest("/registry/health", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getConte... | @Test public void TestGetServiceCenterInstances() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instances... |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceResponse registerMicroservice(Microservice microservice) { try { CreateMicroserviceRequest request = new CreateMicroserviceRequest(); request.setService(microservice); HttpResponse response = httpClient .postHttpRequest("/reg... | @Test public void TestRegistryService() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"serviceId\": \"111111\"}");... |
ServiceCenterClient implements ServiceCenterOperation { @Override public Microservice getMicroserviceByServiceId(String serviceId) { try { HttpResponse response = httpClient.getHttpRequest("/registry/microservices/" + serviceId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { MicroserviceResponse micro... | @Test public void TestGetServiceMessage() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"service\": {\n" +... |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroservicesResponse getMicroserviceList() { try { HttpResponse response = httpClient.getHttpRequest("/registry/microservices", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { return HttpUtils.deserialize(response.getContent(), M... | @Test public void TestGetServiceList() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); MicroservicesResponse microservicesResponse = new Micros... |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceResponse queryServiceId(Microservice microservice) { try { URIBuilder uriBuilder = new URIBuilder("/registry/existence"); uriBuilder.setParameter("type", "microservice"); uriBuilder.setParameter("appId", microservice.getAppId... | @Test public void TestQueryServiceId() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"serviceId\": \"111111\"}"); ... |
ServiceCenterClient implements ServiceCenterOperation { @Override public RegisteredMicroserviceInstanceResponse registerMicroserviceInstance(MicroserviceInstance instance) { try { CreateMicroserviceInstanceRequest request = new CreateMicroserviceInstanceRequest(); request.setInstance(instance); HttpResponse response = ... | @Test public void TestRegisterServiceInstance() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); httpResponse.setContent("{\"instanceId\": \"111... |
ServiceCenterClient implements ServiceCenterOperation { public void deleteMicroserviceInstance(String serviceId, String instanceId) { try { HttpResponse response = httpClient .deleteHttpRequest("/registry/microservices/" + serviceId + "/instances/" + instanceId, null, null); if (response.getStatusCode() == HttpStatus.S... | @Test public void TestDeleteServiceInstance() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.deleteHttpReq... |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstancesResponse getMicroserviceInstanceList(String serviceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/instances", null, null); if (response.getStatusCode() == HttpStatus.S... | @Test public void TestGetServiceInstanceList() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instances\":... |
ServiceCenterClient implements ServiceCenterOperation { @Override public MicroserviceInstance getMicroserviceInstance(String serviceId, String instanceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/instances/" + instanceId, null, null); if (response.getStatusCo... | @Test public void TestGetServiceInstanceMessage() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"instance\... |
ServiceCenterClient implements ServiceCenterOperation { public void sendHeartBeats(HeartbeatsRequest heartbeatsRequest) { try { HttpResponse response = httpClient .putHttpRequest("/registry/heartbeats", null, HttpUtils.serialize(heartbeatsRequest)); if (response.getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("HEART... | @Test public void TestSendHeartBeats() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); HeartbeatsRequest heartbeatsRequest = new HeartbeatsRequ... |
ServiceCenterClient implements ServiceCenterOperation { @Override public boolean updateMicroserviceInstanceStatus(String serviceId, String instanceId, MicroserviceInstanceStatus status) { try { HttpResponse response = httpClient.putHttpRequest( "/registry/microservices/" + serviceId + "/instances/" + instanceId + "/sta... | @Test public void TestUpdateServicesInstanceStatus() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.putHtt... |
ServiceCenterClient implements ServiceCenterOperation { public List<SchemaInfo> getServiceSchemasList(String serviceId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/schemas", null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { GetSchemaListResponse g... | @Test public void TestGetServiceSchemas() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"schemas\": [\n" +... |
ServiceCenterClient implements ServiceCenterOperation { public String getServiceSchemaContext(String serviceId, String schemaId) { try { HttpResponse response = httpClient .getHttpRequest("/registry/microservices/" + serviceId + "/schemas/" + schemaId, null, null); if (response.getStatusCode() == HttpStatus.SC_OK) { Ge... | @Test public void TestGetServiceSchemasContext() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); String responseString = "{\n" + " \"schema\": ... |
DefaultLogPublisher implements MetricsInitializer { @Subscribe public void onPolledEvent(PolledEvent event) { try { printLog(event.getMeters()); } catch (Throwable e) { LOGGER.error("Failed to print perf log.", e); } } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config)... | @Test public void onPolledEvent_failed() { publisher.onPolledEvent(null); LoggingEvent event = collector.getEvents().get(0); Assert.assertEquals("Failed to print perf log.", event.getMessage()); Assert.assertEquals(NullPointerException.class, event.getThrowableInformation().getThrowable().getClass()); }
@Test public vo... |
ServiceCenterClient implements ServiceCenterOperation { @Override public boolean updateServiceSchemaContext(String serviceId, SchemaInfo schemaInfo) { try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaInfo.getSchema()); request.setSummary(schemaInfo.getSummary()); HttpResponse respo... | @Test public void TestUpdateServiceSchema() throws IOException { ServiceCenterRawClient serviceCenterRawClient = Mockito.mock(ServiceCenterRawClient.class); HttpResponse httpResponse = new HttpResponse(); httpResponse.setStatusCode(200); httpResponse.setMessage("ok"); Mockito.when(serviceCenterRawClient.putHttpRequest(... |
TransportConfigUtils { public static int readVerticleCount(String key, String deprecatedKey) { int count = DynamicPropertyFactory.getInstance().getIntProperty(key, -1).get(); if (count > 0) { return count; } count = DynamicPropertyFactory.getInstance().getIntProperty(deprecatedKey, -1).get(); if (count > 0) { LOGGER.wa... | @Test public void readVerticleCount_new_exist() { ArchaiusUtils.setProperty(key, 10); Assert.assertEquals(10, TransportConfigUtils.readVerticleCount(key, deprecatedKey)); }
@Test public void readVerticleCount_old_exist() { ArchaiusUtils.setProperty(deprecatedKey, 10); LogCollector collector = new LogCollector(); Assert... |
HighwayCodec { public static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer) throws Exception { RequestRootDeserializer<Object> requestDeserializer = operationProtobuf.getRequestRootDeserializer(); Map<String, Object> swaggerArguments = requestDese... | @Test public void testDecodeRequestTraceId(@Mocked Endpoint endpoint) throws Exception { commonMock(); Invocation invocation = new Invocation(endpoint, operationMeta, null); invocation.addContext("X-B3-traceId", "test1"); Assert.assertEquals("test1", invocation.getContext("X-B3-traceId")); RequestHeader headers = new R... |
HighwayCodec { public static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema, Object body) throws Exception { try (HighwayOutputStream os = new HighwayOutputStream(msgId)) { os.write(header, bodySchema, body); return os.getBuffer(); } } private HighwayCodec(); static TcpOutpu... | @Test public void testEncodeResponse() { boolean status = true; ResponseRootSerializer bodySchema = Mockito.mock(ResponseRootSerializer.class); try { commonMock(); Object data = new Object(); Mockito.when(bodySchema.serialize(data)).thenReturn(new byte[0]); HighwayCodec.encodeResponse(23432142, null, bodySchema, data);... |
HighwayCodec { public static TcpOutputStream encodeRequest(long msgId, Invocation invocation, OperationProtobuf operationProtobuf) throws Exception { RequestHeader header = new RequestHeader(); header.setMsgType(MsgType.REQUEST); header.setFlags(0); header.setDestMicroservice(invocation.getMicroserviceName()); header.s... | @Test public void testEncodeRequest() { boolean status = true; try { commonMock(); Map<String, Object> args = new HashMap<>(0); Mockito.when(invocation.getInvocationArguments()).thenReturn(args); Mockito.when(requestSerializer.serialize(args)).thenReturn(new byte[0]); TcpOutputStream os = HighwayCodec.encodeRequest(0, ... |
ResponseHeader { public void setContext(Map<String, String> context) { this.context = context; } static RootSerializer getRootSerializer(); static ResponseHeader readObject(Buffer bodyBuffer); int getFlags(); void setFlags(int flags); int getStatusCode(); void setStatusCode(int statusCode); String getReasonPhrase(); v... | @Test public void testSetContext() { context.put("key1", "v1"); responseHeader.setContext(context); Assert.assertNotNull(responseHeader.getContext()); Assert.assertEquals("v1", responseHeader.getContext().get("key1")); } |
HighwayServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocat... | @Test public void should_not_invoke_filter_when_decode_request_failed(@Mocked FilterNode nextNode) throws Exception { mockDecodeRequestFail(); codecFilter.onFilter(invocation, nextNode); new Verifications() { { nextNode.onFilter(invocation); times = 0; } }; }
@Test public void should_convert_exception_to_response_when_... |
HighwayTransport extends AbstractTransport { public boolean init() throws Exception { highwayClient.init(transportVertx); DeploymentOptions deployOptions = new DeploymentOptions().setInstances(HighwayConfig.getServerThreadCount()); setListenAddressWithoutSchema(HighwayConfig.getAddress(), Collections.singletonMap(TcpCo... | @Test public void testInit() { boolean status = true; try { transport.init(); } catch (Exception e) { status = false; } Assert.assertTrue(status); } |
HighwayTransport extends AbstractTransport { @Override public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception { highwayClient.send(invocation, asyncResp); } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testSendException() throws Exception { Invocation invocation = Mockito.mock(Invocation.class); AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class); commonHighwayMock(invocation); Holder<Boolean> sended = new Holder<>(false); new MockUp<HighwayClient>() { @Mock public void send(Invocation invoc... |
HighwayTransport extends AbstractTransport { @Override public String getName() { return Const.HIGHWAY; } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); } | @Test public void testHighway() { Invocation invocation = Mockito.mock(Invocation.class); commonHighwayMock(invocation); Assert.assertEquals("highway", transport.getName()); } |
HighwayConfig { public static int getServerThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.highway.server.verticle-count", "servicecomb.highway.server.thread-count"); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCount();... | @Test public void getServerThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.server.verticle-count", 1); Assert.assertEquals(HighwayConfig.getServerThreadCount(), 1); } |
HighwayConfig { public static int getClientThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.highway.client.verticle-count", "servicecomb.highway.client.thread-count"); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCount();... | @Test public void getClientThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.client.verticle-count", 1); Assert.assertEquals(HighwayConfig.getClientThreadCount(), 1); } |
HighwayConfig { public static String getAddress() { DynamicStringProperty address = DynamicPropertyFactory.getInstance().getStringProperty("servicecomb.highway.address", null); return address.get(); } private HighwayConfig(); static String getAddress(); static int getServerThreadCount(); static int getClientThreadCoun... | @Test public void getAddress() { Assert.assertEquals(HighwayConfig.getAddress(), null); } |
HighwayClient { public void init(Vertx vertx) throws Exception { TcpClientConfig normalConfig = createTcpClientConfig(); normalConfig.setSsl(false); TcpClientConfig sslConfig = createTcpClientConfig(); sslConfig.setSsl(true); clientMgr = new ClientPoolManager<>(vertx, new HighwayClientPoolFactory(normalConfig, sslConfi... | @Test public void testHighwayClientSSL(@Mocked Vertx vertx) throws Exception { new MockUp<VertxUtils>() { @Mock <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls, DeploymentOptions options) { return true; } }; client.init(vertx); ClientPoolManager<HighwayClientConnectionPool> clie... |
RestClientInvocation { public void invoke(Invocation invocation, AsyncResponse asyncResp) throws Exception { this.invocation = invocation; this.asyncResp = asyncResp; OperationMeta operationMeta = invocation.getOperationMeta(); restOperationMeta = operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); String path ... | @Test public void invoke(@Mocked Response resp) throws Exception { doAnswer(a -> { asyncResp.complete(resp); return null; }).when(request).end(); restClientInvocation.invoke(invocation, asyncResp); Assert.assertSame(resp, response); Assert.assertThat(headers.names(), Matchers.containsInAnyOrder(org.apache.servicecomb.c... |
MetricsRestPublisher implements MetricsInitializer { @ApiResponses({ @ApiResponse(code = 400, response = String.class, message = "illegal request content"), }) @GET @Path("/") public Map<String, Double> measure() { Map<String, Double> measurements = new LinkedHashMap<>(); if (globalRegistry == null) { return measuremen... | @Test public void measure_globalRegistryNull() { Map<String, Double> result = publisher.measure(); Assert.assertEquals(0, result.size()); } |
RestClientInvocation { protected void setCseContext() { try { String cseContext = JsonUtils.writeValueAsString(invocation.getContext()); clientRequest.putHeader(org.apache.servicecomb.core.Const.CSE_CONTEXT, cseContext); } catch (Throwable e) { invocation.getTraceIdLogger().error(LOGGER, "Failed to encode and set cseCo... | @Test public void testSetCseContext() { Map<String, String> contextMap = Collections.singletonMap("k", "v"); when(invocation.getContext()).thenReturn(contextMap); restClientInvocation.setCseContext(); Assert.assertEquals("x-cse-context: {\"k\":\"v\"}\n", headers.toString()); }
@Test public void testSetCseContext_failed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.