method2testcases
stringlengths
118
3.08k
### Question: 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 CseException createLoadbalanceException(String code, Throwable cause, Object... args); static final String CSE_HANDLER_LB_WRONG_RULE; }### Answer: @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(cseException); }
### Question: 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(propertiesMap.get(entry.getKey()))) { return false; } } return true; } @Override int getOrder(); @Override boolean enabled(); @Override boolean isGroupingFilter(); }### Answer: @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.allowVisit(instance, filterOptions)); filterOptions.clear(); filterOptions.put("tag0", "value1"); Assert.assertFalse(filter.allowVisit(instance, filterOptions)); }
### Question: 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 transport {}, ignore {}.", transportName, endpoint); return null; } return new ServiceCombServer(transport, new CacheEndpoint(endpoint, instance)); } }### Answer: @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 createEndpointNormal() { new Expectations(transportManager) { { transportManager.findTransport(anyString); result = trasport; } }; MicroserviceInstance instance = new MicroserviceInstance(); instance.setInstanceId("0000001"); ServiceCombServer server = (ServiceCombServer) filter .createEndpoint(Const.RESTFUL, "rest: Assert.assertSame(instance, server.getInstance()); Assert.assertSame(trasport, server.getEndpoint().getTransport()); Assert.assertEquals("rest: }
### Question: 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.getStatusCode() == 503; } else { return true; } } else { return false; } } LoadbalanceHandler(DiscoveryTree discoveryTree); LoadbalanceHandler(); @Override void handle(Invocation invocation, AsyncResponse asyncResp); static final String CONTEXT_KEY_SERVER_LIST; static final String SERVICECOMB_SERVER_ENDPOINT; static final boolean supportDefinedEndpoint; }### Answer: @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(Response.consumerFailResp(new NullPointerException()))); }
### Question: 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(Configuration.INSTANCE.getRetryHandler(microservice), microservice); break; } } LOGGER.debug("Using retry handler {} for microservice {}.", handler.getClass().getName(), microservice); return handler; } static void addExtentionsFactory(ExtensionsFactory factory); static RuleExt createLoadBalancerRule(String microservice); static RetryHandler createRetryHandler(String microservice); }### Answer: @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", extensionsFactories); holder.init(); RetryHandler retryHandler = ExtensionsManager.createRetryHandler("mytest1"); Assert.assertTrue(DefaultLoadBalancerRetryHandler.class.isInstance(retryHandler)); Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), false)); Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), true)); Assert.assertTrue(retryHandler.isRetriableException(new InvocationException(503, "", ""), true)); Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), false)); Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), true)); Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), false)); Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), true)); Assert.assertFalse(retryHandler.isRetriableException(new IOException(), true)); }
### Question: 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(); String getHost(); boolean equals(Object o); int hashCode(); }### Answer: @Test public void testGetEndpoint() { cs.getEndpoint(); assertNotNull(cs.getEndpoint()); }
### Question: 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); ServiceCombServer(Transport transport, CacheEndpoint cacheEndpoint); Endpoint getEndpoint(); MicroserviceInstance getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); }### Answer: @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)); MicroserviceInstance instance2 = new MicroserviceInstance(); instance2.setInstanceId("123456"); other = new ServiceCombServer(transport, new CacheEndpoint("abcd", instance2)); Assert.assertTrue(cs.equals(other)); }
### Question: 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 toString(); String getHost(); boolean equals(Object o); int hashCode(); }### Answer: @Test public void testToStringMethod() { cs.toString(); assertNotNull(cs.toString()); }
### Question: 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 toString(); String getHost(); boolean equals(Object o); int hashCode(); }### Answer: @Test public void testGetHost() { cs.getHost(); assertNotNull(cs.getHost()); }
### Question: 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 getInstance(); String toString(); String getHost(); boolean equals(Object o); int hashCode(); }### Answer: @Test public void testHashCodeMethod() { cs.hashCode(); assertNotNull(cs.hashCode()); }
### Question: 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.TOO_MANY_REQUESTS_STATUS, errorData)); return true; } else { return false; } } @Override void handle(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testQpsController() { AbstractQpsStrategy qpsStrategy = new FixedWindowStrategy(); qpsStrategy.setKey("abc"); qpsStrategy.setQpsLimit(100L); assertFalse(qpsStrategy.isLimitNewRequest()); qpsStrategy.setQpsLimit(1L); assertTrue(qpsStrategy.isLimitNewRequest()); }
### Question: 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(); List<OperationPerf> getOperationPerfs(); OperationPerf getSummary(); void addOperationPerf(OperationPerf operationPerf); }### Answer: @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(MeterInvocationConst.STAGE_TOTAL); Assert.assertEquals(20, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); perfInfo = summary.findStage(MeterInvocationConst.STAGE_EXECUTION); Assert.assertEquals(20, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); }
### Question: 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 getMsMaxLatency(); void setMsMaxLatency(double msMaxLatency); void add(PerfInfo other); double calcMsLatency(); @Override String toString(); }### Answer: @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()); }
### Question: 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) { latencyDistribution = new Integer[operationPerf.getLatencyDistribution().length]; Arrays.fill(latencyDistribution, 0); } for (int idx = 0; idx < operationPerf.getLatencyDistribution().length; idx++) { latencyDistribution[idx] += operationPerf.getLatencyDistribution()[idx]; } } String getOperation(); void setOperation(String operation); Map<String, PerfInfo> getStages(); Integer[] getLatencyDistribution(); void setLatencyDistribution(Integer[] latencyDistribution); void setStages(Map<String, PerfInfo> stages); PerfInfo findStage(String stage); void add(OperationPerf operationPerf); }### Answer: @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.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); perfInfo = opPerf.findStage(MeterInvocationConst.STAGE_EXECUTION); Assert.assertEquals(10, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); }
### Question: CommandKey { public static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation) { return CustomizeCommandGroupKey.asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName(), invocation); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation); static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation); }### Answer: @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(invocation); HystrixCommandGroupKey hystrixCommandGroupKey = CommandKey.toHystrixCommandGroupKey("groupname", invocation); Assert.assertNotNull(hystrixCommandGroupKey); }
### Question: CommandKey { public static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation) { return HystrixCommandKey.Factory .asKey(type + "." + invocation.getOperationMeta().getMicroserviceQualifiedName()); } private CommandKey(); static HystrixCommandGroupKey toHystrixCommandGroupKey(String type, Invocation invocation); static HystrixCommandKey toHystrixCommandKey(String type, Invocation invocation); }### Answer: @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); HystrixCommandKey hystrixCommandGroupKey = CommandKey.toHystrixCommandKey("groupname", invocation); Assert.assertNotNull(hystrixCommandGroupKey); }
### Question: ConsumerBizkeeperHandler extends BizkeeperHandler { @Override protected BizkeeperCommand createBizkeeperCommand(Invocation invocation) { HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); setCommonProperties(invocation, setter); BizkeeperCommand command = new ConsumerBizkeeperCommand(groupname, invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey(groupname, invocation)) .andCommandKey(CommandKey.toHystrixCommandKey(groupname, invocation)) .andCommandPropertiesDefaults(setter)); return command; } ConsumerBizkeeperHandler(); }### Answer: @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(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); CommandKey.toHystrixCommandGroupKey("groupname", invocation); CommandKey.toHystrixCommandKey("groupname", invocation); BizkeeperCommand command = consumerBizkeeperHandler.createBizkeeperCommand(invocation); Assert.assertNotNull(command); }
### Question: BizkeeperRequestContext { public static BizkeeperRequestContext initializeContext() { return new BizkeeperRequestContext(HystrixRequestContext.initializeContext()); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); }### Answer: @Test public void testInitializeContext() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); Assert.assertNotNull(bizkeeperRequestContext); }
### Question: BizkeeperRequestContext { public void shutdown() { this.context.shutdown(); } private BizkeeperRequestContext(HystrixRequestContext context); static BizkeeperRequestContext initializeContext(); void shutdown(); }### Answer: @Test public void testShutdown() { BizkeeperRequestContext bizkeeperRequestContext = BizkeeperRequestContext.initializeContext(); boolean validAssert; try { bizkeeperRequestContext.shutdown(); validAssert = true; } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); }
### Question: BizkeeperHandler implements Handler { protected void setCommonProperties(Invocation invocation, HystrixCommandProperties.Setter setter) { } BizkeeperHandler(String groupname); @Override void handle(Invocation invocation, AsyncResponse asyncResp); }### Answer: @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; } Assert.assertTrue(validAssert); }
### Question: 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); } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Subscribe void onPolledEvent(PolledEvent event); static final String ENABLED; static final String ENDPOINTS_CLIENT_DETAIL_ENABLED; }### Answer: @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 void init_enabled_true() { Holder<Boolean> registered = new Holder<>(); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; ArchaiusUtils.setProperty(DefaultLogPublisher.ENABLED, true); publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertTrue(registered.value); } @Test public void init_enabled_false() { Holder<Boolean> registered = new Holder<>(); new MockUp<EventBus>(eventBus) { @Mock void register(Object object) { registered.value = true; } }; ArchaiusUtils.setProperty(DefaultLogPublisher.ENABLED, false); publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig()); Assert.assertNull(registered.value); }
### Question: 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 CseException createBizkeeperException(String code, Throwable cause, Object... args); static final String SERVICECOMB_BIZKEEPER_FALLBACK; }### Answer: @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(cseException); }
### Question: HystrixPropertiesStrategyExt extends HystrixPropertiesStrategy { public static HystrixPropertiesStrategyExt getInstance() { return INSTANCE; } private HystrixPropertiesStrategyExt(); static HystrixPropertiesStrategyExt getInstance(); @Override HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, Setter builder); }### Answer: @Test public void testGetCommandPropertiesCacheKey() { assertNotNull(HystrixPropertiesStrategyExt.getInstance()); HystrixPropertiesStrategyExt hps = HystrixPropertiesStrategyExt.getInstance(); HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class); Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceName()).thenReturn("testqualify"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false) .withFallbackIsolationSemaphoreMaxConcurrentRequests( Configuration.INSTANCE.getFallbackMaxConcurrentRequests("groupname", "testing", invocation.getOperationMeta().getMicroserviceQualifiedName())); String str1 = hps.getCommandPropertiesCacheKey(commandKey, setter); Assert.assertNull(str1); }
### Question: 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.compareAndSet(false, true)) { eventBus.post(new CircutBreakerEvent(key, Type.OPEN)); } break; case SUCCESS: if (flag.compareAndSet(true, false)) { eventBus.post(new CircutBreakerEvent(key, Type.CLOSE)); } break; default: break; } } @Override void markEvent(HystrixEventType eventType, HystrixCommandKey key); }### Answer: @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, commandKey); Assert.assertEquals(1, taskList.size()); circutBreakerEventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey); Assert.assertEquals(2, taskList.size()); }
### Question: 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.invoke(null, invocation.getContext()); } } catch (Throwable e) { LOG.warn("Failed to execute method DTMContext#{}, please check", DtmConfig.DTM_IMPORT_METHOD, e); } invocation.next(asyncResp); } DtmProviderHandler(); @Override void handle(Invocation invocation, AsyncResponse asyncResp); }### Answer: @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-id"; String expectTraceId = "dtm-trace-id"; context.put(DTMContext.GLOBAL_TX_ID_KEY, expectTxId); context.put(Const.TRACE_ID_NAME, expectTraceId); Assert.assertEquals("", DTMContext.TRACE_ID); Assert.assertEquals("", DTMContext.GLOBAL_TX_ID); providerHandler.handle(invocation, null); Assert.assertEquals(expectTraceId, DTMContext.TRACE_ID); Assert.assertEquals(expectTxId, DTMContext.GLOBAL_TX_ID); }
### Question: 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 CasEnvConfig INSTANCE; }### Answer: @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")); }
### Question: 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, responseStatusCode={}, responseMessage={}, responseContent{}", response.getStatusCode(), response.getMessage(), response.getContent()); } } catch (IOException e) { LOGGER.error("delete keyValue fails", e); } } KieClient(); KieClient(String host, int port, String projectName); KieClient(KieRawClient serviceCenterRawClient); String putKeyValue(String key, KVBody kvBody); List<KVResponse> getValueOfKey(String key); List<KVResponse> searchKeyValueByLabels(Map<String, String> labels); void deleteKeyValue(KVDoc kvDoc); }### Answer: @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("OK"); Mockito.when(kieRawClient.deleteHttpRequest("/kie/kv/?kvID=" + kvDoc.getId(), null, null)) .thenReturn(httpResponse); KieClient kieClient = new KieClient(kieRawClient); kieClient.deleteKeyValue(kvDoc); }
### Question: HighwayCodec { public static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer) throws Exception { RequestRootDeserializer<Object> requestDeserializer = operationProtobuf.getRequestRootDeserializer(); Map<String, Object> swaggerArguments = requestDeserializer.deserialize(bodyBuffer.getBytes()); addPrimitiveTypeDefaultValues(invocation, swaggerArguments); invocation.setSwaggerArguments(swaggerArguments); invocation.mergeContext(header.getContext()); } private HighwayCodec(); static TcpOutputStream encodeRequest(long msgId, Invocation invocation, OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema, Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); }### Answer: @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 RequestHeader(); Map<String, String> context = new HashMap<>(); headers.setContext(context); HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer); Assert.assertEquals("test1", invocation.getContext("X-B3-traceId")); context.put("X-B3-traceId", "test2"); HighwayCodec.decodeRequest(invocation, headers, operationProtobuf, bodyBuffer); Assert.assertEquals("test2", invocation.getContext("X-B3-traceId")); }
### Question: 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 TcpOutputStream encodeRequest(long msgId, Invocation invocation, OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema, Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); }### Answer: @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); } catch (Exception e) { e.printStackTrace(); status = false; } Assert.assertTrue(status); }
### Question: 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.setSchemaId(invocation.getSchemaId()); header.setOperationName(invocation.getOperationName()); header.setContext(invocation.getContext()); HighwayOutputStream os = new HighwayOutputStream(msgId); os.write(header, operationProtobuf.getRequestRootSerializer(), invocation.getSwaggerArguments()); return os; } private HighwayCodec(); static TcpOutputStream encodeRequest(long msgId, Invocation invocation, OperationProtobuf operationProtobuf); static void decodeRequest(Invocation invocation, RequestHeader header, OperationProtobuf operationProtobuf, Buffer bodyBuffer); static RequestHeader readRequestHeader(Buffer headerBuffer); static Buffer encodeResponse(long msgId, ResponseHeader header, ResponseRootSerializer bodySchema, Object body); static Response decodeResponse(Invocation invocation, OperationProtobuf operationProtobuf, TcpData tcpData); }### Answer: @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, invocation, operationProtobuf); Assert.assertNotNull(os); Assert.assertArrayEquals(TcpParser.TCP_MAGIC, os.getBuffer().getBytes(0, 7)); } catch (Exception e) { e.printStackTrace(); status = false; } Assert.assertTrue(status); }
### Question: 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(); void setReasonPhrase(String reason); Map<String, String> getContext(); void setContext(Map<String, String> context); Headers getHeaders(); void setHeaders(Headers headers); }### Answer: @Test public void testSetContext() { context.put("key1", "v1"); responseHeader.setContext(context); Assert.assertNotNull(responseHeader.getContext()); Assert.assertEquals("v1", responseHeader.getContext().get("key1")); }
### Question: 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(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); }### Answer: @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_decode_request_failed() throws Exception { mockDecodeRequestFail(); Response response = codecFilter.onFilter(invocation, nextNode).get(); assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR); assertThat(Json.encode(response.getResult())) .isEqualTo("{\"code\":\"SCB.50000000\",\"message\":\"encode request failed\"}"); }
### Question: HighwayTransport extends AbstractTransport { public boolean init() throws Exception { highwayClient.init(transportVertx); DeploymentOptions deployOptions = new DeploymentOptions().setInstances(HighwayConfig.getServerThreadCount()); setListenAddressWithoutSchema(HighwayConfig.getAddress(), Collections.singletonMap(TcpConst.LOGIN, "true")); SimpleJsonObject json = new SimpleJsonObject(); json.put(ENDPOINT_KEY, getEndpoint()); deployOptions.setConfig(json); deployOptions.setWorkerPoolName("pool-worker-transport-highway"); return VertxUtils.blockDeploy(transportVertx, HighwayServerVerticle.class, deployOptions); } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testInit() { boolean status = true; try { transport.init(); } catch (Exception e) { status = false; } Assert.assertTrue(status); }
### Question: 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); }### Answer: @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 invocation, AsyncResponse asyncResp) throws Exception { sended.value = true; } }; transport.send(invocation, asyncResp); Assert.assertTrue(sended.value); }
### Question: HighwayTransport extends AbstractTransport { @Override public String getName() { return Const.HIGHWAY; } @Override String getName(); boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testHighway() { Invocation invocation = Mockito.mock(Invocation.class); commonHighwayMock(invocation); Assert.assertEquals("highway", transport.getName()); }
### Question: 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(); }### Answer: @Test public void getServerThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.server.verticle-count", 1); Assert.assertEquals(HighwayConfig.getServerThreadCount(), 1); }
### Question: 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(); }### Answer: @Test public void getClientThreadCount() { ArchaiusUtils.setProperty("servicecomb.highway.client.verticle-count", 1); Assert.assertEquals(HighwayConfig.getClientThreadCount(), 1); }
### Question: 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 getClientThreadCount(); }### Answer: @Test public void getAddress() { Assert.assertEquals(HighwayConfig.getAddress(), null); }
### Question: 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, sslConfig)); DeploymentOptions deployOptions = VertxUtils.createClientDeployOptions(clientMgr, HighwayConfig.getClientThreadCount()); VertxUtils.blockDeploy(vertx, ClientVerticle.class, deployOptions); } void init(Vertx vertx); void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @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> clientMgr = Deencapsulation.getField(client, "clientMgr"); Assert.assertSame(vertx, Deencapsulation.getField(clientMgr, "vertx")); }
### Question: 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 measurements; } StringBuilder sb = new StringBuilder(); for (Registry registry : globalRegistry.getRegistries()) { for (Meter meter : registry) { meter.measure().forEach(measurement -> { String key = idToString(measurement.id(), sb); measurements.put(key, measurement.value()); }); } } return measurements; } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @ApiResponses({ @ApiResponse(code = 400, response = String.class, message = "illegal request content"), }) @GET @Path("/") Map<String, Double> measure(); }### Answer: @Test public void measure_globalRegistryNull() { Map<String, Double> result = publisher.measure(); Assert.assertEquals(0, result.size()); }
### Question: 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 cseContext, message={}." , ExceptionUtils.getExceptionMessageWithoutTrace(e)); } } RestClientInvocation(HttpClientWithContext httpClientWithContext, List<HttpClientFilter> httpClientFilters); void invoke(Invocation invocation, AsyncResponse asyncResp); }### Answer: @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() throws JsonProcessingException { LogCollector logCollector = new LogCollector(); logCollector.setLogLevel(RestClientInvocation.class.getName(), Level.DEBUG); new Expectations(JsonUtils.class) { { JsonUtils.writeValueAsString(any); result = new RuntimeExceptionWithoutStackTrace(); } }; restClientInvocation.setCseContext(); Assert.assertEquals( "Failed to encode and set cseContext, message=cause:RuntimeExceptionWithoutStackTrace,message:null.", logCollector.getEvents().get(0).getMessage()); logCollector.teardown(); }
### Question: PublishUtils { public static PerfInfo createPerfInfo(MeasurementNode stageNode) { PerfInfo perfInfo = new PerfInfo(); perfInfo.setTps(stageNode.findChild(Statistic.count.name()).summary()); perfInfo.setMsTotalTime(stageNode.findChild(Statistic.totalTime.name()).summary() * 1000); MeasurementNode maxNode = stageNode.findChild(Statistic.max.name()); if (maxNode != null) { perfInfo.setMsMaxLatency(maxNode.summary() * 1000); } return perfInfo; } private PublishUtils(); static PerfInfo createPerfInfo(MeasurementNode stageNode); static OperationPerf createOperationPerf(String operation, MeasurementNode statusNode); static void addOperationPerfGroups(OperationPerfGroups operationPerfGroups, String transport, String operation, MeasurementNode statusNode); }### Answer: @Test public void createPerfInfo() { MeasurementNode stageNode = Utils.createStageNode(MeterInvocationConst.STAGE_TOTAL, 10, 10, 100); PerfInfo perf = PublishUtils.createPerfInfo(stageNode); Assert.assertEquals(10, perf.getTps(), 0); Assert.assertEquals(1000, perf.calcMsLatency(), 0); Assert.assertEquals(100000, perf.getMsMaxLatency(), 0); }
### Question: DefaultHttpClientFilter implements HttpClientFilter { @Override public int getOrder() { return Integer.MAX_VALUE; } @Override int getOrder(); @Override boolean enabled(); @Override void beforeSendRequest(Invocation invocation, HttpServletRequestEx requestEx); @Override Response afterReceiveResponse(Invocation invocation, HttpServletResponseEx responseEx); }### Answer: @Test public void testOrder() { Assert.assertEquals(Integer.MAX_VALUE, filter.getOrder()); }
### Question: DefaultHttpClientFilter implements HttpClientFilter { protected ProduceProcessor findProduceProcessor(RestOperationMeta restOperation, HttpServletResponseEx responseEx) { String contentType = responseEx.getHeader(HttpHeaders.CONTENT_TYPE); if (contentType == null) { return null; } String contentTypeForFind = contentType; int idx = contentType.indexOf(';'); if (idx != -1) { contentTypeForFind = contentType.substring(0, idx); } return restOperation.findProduceProcessor(contentTypeForFind); } @Override int getOrder(); @Override boolean enabled(); @Override void beforeSendRequest(Invocation invocation, HttpServletRequestEx requestEx); @Override Response afterReceiveResponse(Invocation invocation, HttpServletResponseEx responseEx); }### Answer: @Test public void testFindProduceProcessorNullContentType(@Mocked RestOperationMeta restOperation, @Mocked HttpServletResponseEx responseEx) { new Expectations() { { responseEx.getHeader(HttpHeaders.CONTENT_TYPE); result = null; } }; Assert.assertNull(filter.findProduceProcessor(restOperation, responseEx)); } @Test public void testFindProduceProcessorJson(@Mocked RestOperationMeta restOperation, @Mocked HttpServletResponseEx responseEx, @Mocked ProduceProcessor produceProcessor) { new Expectations() { { responseEx.getHeader(HttpHeaders.CONTENT_TYPE); result = "json"; restOperation.findProduceProcessor("json"); result = produceProcessor; } }; Assert.assertSame(produceProcessor, filter.findProduceProcessor(restOperation, responseEx)); } @Test public void testFindProduceProcessorJsonWithCharset(@Mocked RestOperationMeta restOperation, @Mocked HttpServletResponseEx responseEx, @Mocked ProduceProcessor produceProcessor) { new Expectations() { { responseEx.getHeader(HttpHeaders.CONTENT_TYPE); result = "json; UTF-8"; restOperation.findProduceProcessor("json"); result = produceProcessor; } }; Assert.assertSame(produceProcessor, filter.findProduceProcessor(restOperation, responseEx)); }
### Question: DefaultHttpClientFilter implements HttpClientFilter { @Override public Response afterReceiveResponse(Invocation invocation, HttpServletResponseEx responseEx) { Response response = extractResponse(invocation, responseEx); for (String headerName : responseEx.getHeaderNames()) { if (headerName.equals(":status")) { continue; } Collection<String> headerValues = responseEx.getHeaders(headerName); for (String headerValue : headerValues) { response.getHeaders().addHeader(headerName, headerValue); } } return response; } @Override int getOrder(); @Override boolean enabled(); @Override void beforeSendRequest(Invocation invocation, HttpServletRequestEx requestEx); @Override Response afterReceiveResponse(Invocation invocation, HttpServletResponseEx responseEx); }### Answer: @Test public void testAfterReceiveResponseNullProduceProcessor(@Mocked Invocation invocation, @Mocked HttpServletResponseEx responseEx, @Mocked OperationMeta operationMeta, @Mocked RestOperationMeta swaggerRestOperation) throws Exception { CommonExceptionData data = new CommonExceptionData("abcd"); new Expectations() { { invocation.getOperationMeta(); result = operationMeta; operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); result = swaggerRestOperation; invocation.findResponseType(403); result = SimpleType.constructUnsafe(CommonExceptionData.class); responseEx.getStatus(); result = 403; responseEx.getStatusType(); result = Status.FORBIDDEN; responseEx.getBodyBuffer(); result = Buffer.buffer(JsonUtils.writeValueAsString(data).getBytes()); } }; Response response = filter.afterReceiveResponse(invocation, responseEx); Assert.assertEquals(403, response.getStatusCode()); Assert.assertEquals("Forbidden", response.getReasonPhrase()); Assert.assertEquals(InvocationException.class, response.<InvocationException>getResult().getClass()); InvocationException invocationException = response.getResult(); Assert.assertEquals( 403, invocationException.getStatusCode()); Assert.assertEquals( "CommonExceptionData [message=abcd]", invocationException.getErrorData().toString()); }
### Question: PublishUtils { public static OperationPerf createOperationPerf(String operation, MeasurementNode statusNode) { OperationPerf operationPerf = new OperationPerf(); operationPerf.setOperation(operation); MeasurementNode stageNode = statusNode.findChild(MeterInvocationConst.TAG_STAGE); stageNode.getChildren().values().forEach(mNode -> { PerfInfo perfInfo = createPerfInfo(mNode); operationPerf.getStages().put(mNode.getName(), perfInfo); }); MeasurementNode latencyNode = statusNode.findChild(MeterInvocationConst.TAG_LATENCY_DISTRIBUTION); if (latencyNode != null && latencyNode.getMeasurements() != null) { operationPerf.setLatencyDistribution(latencyNode.getMeasurements().stream() .map(m -> (int) m.value()) .toArray(Integer[]::new)); } return operationPerf; } private PublishUtils(); static PerfInfo createPerfInfo(MeasurementNode stageNode); static OperationPerf createOperationPerf(String operation, MeasurementNode statusNode); static void addOperationPerfGroups(OperationPerfGroups operationPerfGroups, String transport, String operation, MeasurementNode statusNode); }### Answer: @Test public void createOperationPerf() { OperationPerf opPerf = Utils.createOperationPerf(op); PerfInfo perfInfo = opPerf.findStage(MeterInvocationConst.STAGE_TOTAL); Integer[] latencyDistribution = opPerf.getLatencyDistribution(); Assert.assertEquals(10, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); Assert.assertEquals(2, latencyDistribution.length); Assert.assertEquals(1, latencyDistribution[0].intValue()); Assert.assertEquals(2, latencyDistribution[1].intValue()); }
### Question: TransportClientConfig { public static int getThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.rest.client.verticle-count", "servicecomb.rest.client.thread-count"); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getThreadCount() { ArchaiusUtils.setProperty("servicecomb.rest.client.verticle-count", 1); Assert.assertEquals(1, TransportClientConfig.getThreadCount()); }
### Question: TransportClientConfig { public static int getConnectionMaxPoolSize() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.client.connection.maxPoolSize", HttpClientOptions.DEFAULT_MAX_POOL_SIZE) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getConnectionMaxPoolSize() { Assert.assertEquals(5, TransportClientConfig.getConnectionMaxPoolSize()); }
### Question: TransportClientConfig { public static int getConnectionIdleTimeoutInSeconds() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.client.connection.idleTimeoutInSeconds", 60) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getConnectionIdleTimeoutInSeconds() { Assert.assertEquals(60, TransportClientConfig.getConnectionIdleTimeoutInSeconds()); }
### Question: TransportClientConfig { public static int getHttp2MultiplexingLimit() { return DynamicPropertyFactory.getInstance().getIntProperty("servicecomb.rest.client.http2.multiplexingLimit", HttpClientOptions.DEFAULT_HTTP2_MULTIPLEXING_LIMIT) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getHttp2MultiplexingLimit() { Assert.assertEquals(-1, TransportClientConfig.getHttp2MultiplexingLimit()); }
### Question: TransportClientConfig { public static int getHttp2ConnectionMaxPoolSize() { return DynamicPropertyFactory.getInstance().getIntProperty("servicecomb.rest.client.http2.maxPoolSize", HttpClientOptions.DEFAULT_HTTP2_MAX_POOL_SIZE) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getHttp2ConnectionMaxPoolSize() { Assert.assertEquals(1, TransportClientConfig.getHttp2ConnectionMaxPoolSize()); }
### Question: TransportClientConfig { public static int getHttp2ConnectionIdleTimeoutInSeconds() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.client.http2.idleTimeoutInSeconds", TCPSSLOptions.DEFAULT_IDLE_TIMEOUT) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getHttp2ConnectionIdleTimeoutInSeconds() { Assert.assertEquals(0, TransportClientConfig.getHttp2ConnectionIdleTimeoutInSeconds()); }
### Question: TransportClientConfig { public static boolean getUseAlpn() { return DynamicPropertyFactory.getInstance() .getBooleanProperty("servicecomb.rest.client.http2.useAlpnEnabled", true) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getUseAlpnEnabled() { Assert.assertTrue(TransportClientConfig.getUseAlpn()); }
### Question: TransportClientConfig { public static boolean getConnectionKeepAlive() { return DynamicPropertyFactory.getInstance() .getBooleanProperty("servicecomb.rest.client.connection.keepAlive", HttpClientOptions.DEFAULT_KEEP_ALIVE) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getConnectionKeepAlive() { Assert.assertTrue(TransportClientConfig.getConnectionKeepAlive()); }
### Question: TransportClientConfig { public static boolean getConnectionCompression() { return DynamicPropertyFactory.getInstance() .getBooleanProperty("servicecomb.rest.client.connection.compression", HttpClientOptions.DEFAULT_TRY_USE_COMPRESSION) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getConnectionCompression() { Assert.assertFalse(TransportClientConfig.getConnectionCompression()); }
### Question: TransportClientConfig { public static int getMaxHeaderSize() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.client.maxHeaderSize", HttpClientOptions.DEFAULT_MAX_HEADER_SIZE) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getMaxHeaderSize() { Assert.assertEquals(8192, TransportClientConfig.getMaxHeaderSize()); ArchaiusUtils.setProperty("servicecomb.rest.client.maxHeaderSize", 1024); Assert.assertEquals(1024, TransportClientConfig.getMaxHeaderSize()); }
### Question: PublishUtils { public static void addOperationPerfGroups(OperationPerfGroups operationPerfGroups, String transport, String operation, MeasurementNode statusNode) { Map<String, OperationPerfGroup> statusMap = operationPerfGroups .getGroups() .computeIfAbsent(transport, tn -> new HashMap<>()); OperationPerfGroup group = statusMap .computeIfAbsent(statusNode.getName(), status -> new OperationPerfGroup(transport, status)); OperationPerf operationPerf = createOperationPerf(operation, statusNode); group.addOperationPerf(operationPerf); } private PublishUtils(); static PerfInfo createPerfInfo(MeasurementNode stageNode); static OperationPerf createOperationPerf(String operation, MeasurementNode statusNode); static void addOperationPerfGroups(OperationPerfGroups operationPerfGroups, String transport, String operation, MeasurementNode statusNode); }### Answer: @Test public void addOperationPerfGroups() { OperationPerfGroups groups = new OperationPerfGroups(); PublishUtils.addOperationPerfGroups(groups, Const.RESTFUL, op, Utils.createStatusNode(Status.OK.name(), Utils.totalStageNode)); Map<String, OperationPerfGroup> statusMap = groups.getGroups().get(Const.RESTFUL); OperationPerfGroup group = statusMap.get(Status.OK.name()); PerfInfo perfInfo = group.getSummary().findStage(MeterInvocationConst.STAGE_TOTAL); Integer[] latencyDistribution = group.getSummary().getLatencyDistribution(); Assert.assertEquals(10, perfInfo.getTps(), 0); Assert.assertEquals(1000, perfInfo.calcMsLatency(), 0); Assert.assertEquals(100000, perfInfo.getMsMaxLatency(), 0); Assert.assertEquals(2, latencyDistribution.length); Assert.assertEquals(1, latencyDistribution[0].intValue()); Assert.assertEquals(2, latencyDistribution[1].intValue()); }
### Question: TransportClientConfig { public static int getMaxWaitQueueSize() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.client.maxWaitQueueSize", HttpClientOptions.DEFAULT_MAX_WAIT_QUEUE_SIZE) .get(); } private TransportClientConfig(); static Class<? extends RestTransportClient> getRestTransportClientCls(); static void setRestTransportClientCls(Class<? extends RestTransportClient> restTransportClientCls); static int getThreadCount(); static int getHttp2ConnectionMaxPoolSize(); static int getHttp2MultiplexingLimit(); static int getHttp2ConnectionIdleTimeoutInSeconds(); static boolean getUseAlpn(); static boolean isHttp2TransportClientEnabled(); static int getConnectionMaxPoolSize(); static int getConnectionIdleTimeoutInSeconds(); static boolean getConnectionKeepAlive(); static boolean getConnectionCompression(); static int getMaxHeaderSize(); static int getMaxWaitQueueSize(); static boolean isHttpTransportClientEnabled(); static int getConnectionTimeoutInMillis(); }### Answer: @Test public void getMaxWaitQueueSize() { Assert.assertEquals(-1, TransportClientConfig.getMaxWaitQueueSize()); ArchaiusUtils.setProperty("servicecomb.rest.client.maxWaitQueueSize", 1024); Assert.assertEquals(1024, TransportClientConfig.getMaxWaitQueueSize()); }
### Question: RestTransportClient { public void send(Invocation invocation, AsyncResponse asyncResp) { HttpClientWithContext httpClientWithContext = findHttpClientPool(invocation); RestClientInvocation restClientInvocation = new RestClientInvocation(httpClientWithContext, httpClientFilters); try { restClientInvocation.invoke(invocation, asyncResp); } catch (Throwable e) { asyncResp.fail(invocation.getInvocationType(), e); LOGGER.error("vertx rest transport send error.", e); } } void init(Vertx vertx); void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testRestTransportClientException() { boolean status = true; Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta); Mockito.when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(operationMeta); try { instance.send(invocation, asyncResp); } catch (Exception e) { status = false; } Assert.assertFalse(status); }
### Question: TransportConfig { public static String getAddress() { DynamicStringProperty address = DynamicPropertyFactory.getInstance().getStringProperty("servicecomb.rest.address", null); return address.get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetAddressNull() { Assert.assertNull(TransportConfig.getAddress()); } @Test public void testGetAddressNormal() { ArchaiusUtils.setProperty("servicecomb.rest.address", "1.1.1.1"); Assert.assertEquals("1.1.1.1", TransportConfig.getAddress()); }
### Question: TransportConfig { public static int getThreadCount() { return TransportConfigUtils.readVerticleCount( "servicecomb.rest.server.verticle-count", "servicecomb.rest.server.thread-count"); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetThreadCountNull() { new MockUp<Runtime>() { @Mock int availableProcessors() { return 1; } }; Assert.assertEquals(1, TransportConfig.getThreadCount()); } @Test public void testGetThreadCountNormal() { ArchaiusUtils.setProperty("servicecomb.rest.server.thread-count", 10); Assert.assertEquals(10, TransportConfig.getThreadCount()); }
### Question: TransportConfig { public static boolean isCorsEnabled() { return DynamicPropertyFactory.getInstance() .getBooleanProperty(SERVICECOMB_CORS_CONFIG_BASE + ".enabled", false) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testIsCorsEnabled() { Assert.assertFalse(TransportConfig.isCorsEnabled()); ArchaiusUtils.setProperty("servicecomb.cors.enabled", true); Assert.assertTrue(TransportConfig.isCorsEnabled()); ArchaiusUtils.setProperty("servicecomb.cors.enabled", false); Assert.assertFalse(TransportConfig.isCorsEnabled()); }
### Question: TransportConfig { public static String getCorsAllowedOrigin() { return DynamicPropertyFactory.getInstance() .getStringProperty(SERVICECOMB_CORS_CONFIG_BASE + ".origin", "*") .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetCorsAllowedOrigin() { Assert.assertEquals("*", TransportConfig.getCorsAllowedOrigin()); String origin = "http: ArchaiusUtils.setProperty("servicecomb.cors.origin", origin); Assert.assertEquals(origin, TransportConfig.getCorsAllowedOrigin()); }
### Question: TransportConfig { public static boolean isCorsAllowCredentials() { return DynamicPropertyFactory.getInstance() .getBooleanProperty(SERVICECOMB_CORS_CONFIG_BASE + ".allowCredentials", false) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testIsCorsAllowCredentials() { Assert.assertFalse(TransportConfig.isCorsAllowCredentials()); ArchaiusUtils.setProperty("servicecomb.cors.allowCredentials", true); Assert.assertTrue(TransportConfig.isCorsAllowCredentials()); ArchaiusUtils.setProperty("servicecomb.cors.allowCredentials", false); Assert.assertFalse(TransportConfig.isCorsAllowCredentials()); }
### Question: TransportConfig { public static Set<String> getCorsAllowedHeaders() { String allowedHeaders = DynamicPropertyFactory.getInstance() .getStringProperty(SERVICECOMB_CORS_CONFIG_BASE + ".allowedHeader", null) .get(); return convertToSet(allowedHeaders); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetCorsAllowedHeaders() { String configKey = "servicecomb.cors.allowedHeader"; Assert.assertTrue(TransportConfig.getCorsAllowedHeaders().isEmpty()); ArchaiusUtils.setProperty(configKey, "abc"); Assert.assertThat(TransportConfig.getCorsAllowedHeaders(), Matchers.containsInAnyOrder("abc")); ArchaiusUtils.setProperty(configKey, "abc, def"); Assert.assertThat(TransportConfig.getCorsAllowedHeaders(), Matchers.containsInAnyOrder("abc", "def")); ArchaiusUtils.setProperty(configKey, "abc ,, def"); Assert.assertThat(TransportConfig.getCorsAllowedHeaders(), Matchers.containsInAnyOrder("abc", "def")); ArchaiusUtils.setProperty(configKey, ""); Assert.assertTrue(TransportConfig.getCorsAllowedHeaders().isEmpty()); }
### Question: TransportConfig { public static Set<String> getCorsAllowedMethods() { String allowedMethods = DynamicPropertyFactory.getInstance() .getStringProperty(SERVICECOMB_CORS_CONFIG_BASE + ".allowedMethod", null) .get(); return convertToSet(allowedMethods); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetCorsAllowedMethods() { String configKey = "servicecomb.cors.allowedMethod"; Assert.assertTrue(TransportConfig.getCorsAllowedMethods().isEmpty()); ArchaiusUtils.setProperty(configKey, "GET"); Assert.assertThat(TransportConfig.getCorsAllowedMethods(), Matchers.containsInAnyOrder("GET")); ArchaiusUtils.setProperty(configKey, "GET, POST"); Assert.assertThat(TransportConfig.getCorsAllowedMethods(), Matchers.containsInAnyOrder("GET", "POST")); ArchaiusUtils.setProperty(configKey, "GET,,POST"); Assert.assertThat(TransportConfig.getCorsAllowedMethods(), Matchers.containsInAnyOrder("GET", "POST")); ArchaiusUtils.setProperty(configKey, ""); Assert.assertTrue(TransportConfig.getCorsAllowedMethods().isEmpty()); }
### Question: TransportConfig { public static Set<String> getCorsExposedHeaders() { String exposedHeaders = DynamicPropertyFactory.getInstance() .getStringProperty(SERVICECOMB_CORS_CONFIG_BASE + ".exposedHeader", null) .get(); return convertToSet(exposedHeaders); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetCorsExposedHeaders() { String configKey = "servicecomb.cors.exposedHeader"; Assert.assertTrue(TransportConfig.getCorsExposedHeaders().isEmpty()); ArchaiusUtils.setProperty(configKey, "abc"); Assert.assertThat(TransportConfig.getCorsExposedHeaders(), Matchers.containsInAnyOrder("abc")); ArchaiusUtils.setProperty(configKey, "abc, def"); Assert.assertThat(TransportConfig.getCorsExposedHeaders(), Matchers.containsInAnyOrder("abc", "def")); ArchaiusUtils.setProperty(configKey, "abc ,, def"); Assert.assertThat(TransportConfig.getCorsExposedHeaders(), Matchers.containsInAnyOrder("abc", "def")); ArchaiusUtils.setProperty(configKey, ""); Assert.assertTrue(TransportConfig.getCorsExposedHeaders().isEmpty()); }
### Question: TransportConfig { public static int getCorsMaxAge() { return DynamicPropertyFactory.getInstance() .getIntProperty(SERVICECOMB_CORS_CONFIG_BASE + ".maxAge", -1) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetCorsMaxAge() { Assert.assertEquals(-1, TransportConfig.getCorsMaxAge()); ArchaiusUtils.setProperty("servicecomb.cors.maxAge", 3600); Assert.assertEquals(3600, TransportConfig.getCorsMaxAge()); }
### Question: TransportConfig { public static long getMaxConcurrentStreams() { return DynamicPropertyFactory.getInstance() .getLongProperty("servicecomb.rest.server.http2.concurrentStreams", HttpServerOptions.DEFAULT_INITIAL_SETTINGS_MAX_CONCURRENT_STREAMS) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testMaxConcurrentStreams() { Assert.assertEquals(100L, TransportConfig.getMaxConcurrentStreams()); ArchaiusUtils.setProperty("servicecomb.rest.server.http2.concurrentStreams", 200L); Assert.assertEquals(200L, TransportConfig.getMaxConcurrentStreams()); }
### Question: TransportConfig { public static boolean getUseAlpn() { return DynamicPropertyFactory.getInstance() .getBooleanProperty("servicecomb.rest.server.http2.useAlpnEnabled", true) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testUseAlpn() { Assert.assertTrue(TransportConfig.getUseAlpn()); ArchaiusUtils.setProperty("servicecomb.rest.server.http2.useAlpnEnabled", false); Assert.assertFalse(TransportConfig.getUseAlpn()); }
### Question: TransportConfig { public static int getMaxInitialLineLength() { return DynamicPropertyFactory.getInstance() .getIntProperty("servicecomb.rest.server.maxInitialLineLength", HttpServerOptions.DEFAULT_MAX_INITIAL_LINE_LENGTH) .get(); } private TransportConfig(); static Class<? extends Verticle> getRestServerVerticle(); static void setRestServerVerticle(Class<? extends Verticle> restServerVerticle); static String getAddress(); static int getThreadCount(); static int getConnectionIdleTimeoutInSeconds(); static boolean getCompressed(); static long getMaxConcurrentStreams(); static boolean getUseAlpn(); static int getMaxHeaderSize(); static boolean isCorsEnabled(); static String getCorsAllowedOrigin(); static boolean isCorsAllowCredentials(); static Set<String> getCorsAllowedHeaders(); static Set<String> getCorsAllowedMethods(); static Set<String> getCorsExposedHeaders(); static int getCorsMaxAge(); static int getMaxInitialLineLength(); static final int DEFAULT_SERVER_CONNECTION_IDLE_TIMEOUT_SECOND; static final boolean DEFAULT_SERVER_COMPRESSION_SUPPORT; static final int DEFAULT_SERVER_MAX_HEADER_SIZE; static final String SERVICECOMB_CORS_CONFIG_BASE; }### Answer: @Test public void testGetMaxInitialLineLength() { Assert.assertEquals(4096, TransportConfig.getMaxInitialLineLength()); ArchaiusUtils.setProperty("servicecomb.rest.server.maxInitialLineLength", 8000); Assert.assertEquals(8000, TransportConfig.getMaxInitialLineLength()); }
### Question: VertxRestTransport extends AbstractTransport { @Override public String getName() { return Const.RESTFUL; } @Override String getName(); @Override int getOrder(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testGetName() { Assert.assertEquals("rest", instance.getName()); }
### Question: VertxRestTransport extends AbstractTransport { @Override public boolean init() throws Exception { restClient = RestTransportClientManager.INSTANCE.getRestClient(); DeploymentOptions options = new DeploymentOptions().setInstances(TransportConfig.getThreadCount()); SimpleJsonObject json = new SimpleJsonObject(); json.put(ENDPOINT_KEY, getEndpoint()); json.put(RestTransportClient.class.getName(), restClient); options.setConfig(json); options.setWorkerPoolName("pool-worker-transport-rest"); options.setWorkerPoolSize(VertxOptions.DEFAULT_WORKER_POOL_SIZE); return VertxUtils.blockDeploy(transportVertx, TransportConfig.getRestServerVerticle(), options); } @Override String getName(); @Override int getOrder(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testInit() { boolean status = false; try { new MockUp<VertxUtils>() { @Mock public Vertx init(VertxOptions vertxOptions) { return null; } @Mock public <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls, DeploymentOptions options) throws InterruptedException { return true; } }; instance.init(); } catch (Exception e) { status = true; } Assert.assertFalse(status); }
### Question: VertxRestTransport extends AbstractTransport { @Override public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception { restClient.send(invocation, asyncResp); } @Override String getName(); @Override int getOrder(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testSendException() { boolean validAssert; Invocation invocation = Mockito.mock(Invocation.class); AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class); URIEndpointObject endpoint = Mockito.mock(URIEndpointObject.class); Endpoint end = Mockito.mock(Endpoint.class); Mockito.when(invocation.getEndpoint()).thenReturn(end); Mockito.when(invocation.getEndpoint().getAddress()).thenReturn(endpoint); try { validAssert = true; instance.send(invocation, asyncResp); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
### Question: VertxRestTransport extends AbstractTransport { @Override public int getOrder() { return -1000; } @Override String getName(); @Override int getOrder(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testGetOrder() { VertxRestTransport transport = new VertxRestTransport(); Assert.assertEquals(-1000, transport.getOrder()); }
### Question: VertxRestTransport extends AbstractTransport { @Override public boolean canInit() { setListenAddressWithoutSchema(TransportConfig.getAddress()); URIEndpointObject ep = (URIEndpointObject) getEndpoint().getAddress(); if (ep == null) { return true; } if (!NetUtils.canTcpListen(ep.getSocketAddress().getAddress(), ep.getPort())) { LOGGER.warn( "Can not start VertxRestTransport, the port:{} may have been occupied. You can ignore this message if you are using a web container like tomcat.", ep.getPort()); return false; } return true; } @Override String getName(); @Override int getOrder(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testCanInitNullAddress() throws IOException { new Expectations(TransportConfig.class) { { TransportConfig.getAddress(); result = null; } }; VertxRestTransport transport = new VertxRestTransport(); Assert.assertTrue(transport.canInit()); } @Test public void testCanInitListened() throws IOException { ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); new Expectations(TransportConfig.class) { { TransportConfig.getAddress(); result = "0.0.0.0:" + port; } }; VertxRestTransport transport = new VertxRestTransport(); Assert.assertFalse(transport.canInit()); ss.close(); } @Test public void testCanInitNotListened() throws IOException { ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); ss.close(); new Expectations(TransportConfig.class) { { TransportConfig.getAddress(); result = "0.0.0.0:" + port; } }; VertxRestTransport transport = new VertxRestTransport(); Assert.assertTrue(transport.canInit()); }
### Question: AbstractVertxHttpDispatcher implements VertxHttpDispatcher { protected BodyHandler createBodyHandler() { RestBodyHandler bodyHandler = new RestBodyHandler(); UploadConfig uploadConfig = new UploadConfig(); bodyHandler.setUploadsDirectory(uploadConfig.getLocation()); bodyHandler.setDeleteUploadedFilesOnEnd(true); bodyHandler.setBodyLimit(uploadConfig.getMaxSize()); if (uploadConfig.toMultipartConfigElement() != null) { LOGGER.info("set uploads directory to \"{}\".", uploadConfig.getLocation()); } return bodyHandler; } }### Answer: @Test public void createBodyHandlerUploadNull() { AbstractVertxHttpDispatcher dispatcher = new AbstractVertxHttpDispatcherForTest(); RestBodyHandler bodyHandler = (RestBodyHandler) dispatcher.createBodyHandler(); Assert.assertTrue(Deencapsulation.getField(bodyHandler, "deleteUploadedFilesOnEnd")); Assert.assertNull(Deencapsulation.getField(bodyHandler, "uploadsDir")); } @Test public void createBodyHandlerUploadNormal() { config.setProperty("servicecomb.uploads.directory", "/path"); AbstractVertxHttpDispatcher dispatcher = new AbstractVertxHttpDispatcherForTest(); RestBodyHandler bodyHandler = (RestBodyHandler) dispatcher.createBodyHandler(); Assert.assertTrue(Deencapsulation.getField(bodyHandler, "deleteUploadedFilesOnEnd")); Assert.assertEquals("/path", Deencapsulation.getField(bodyHandler, "uploadsDir")); }
### Question: VertxRestDispatcher extends AbstractVertxHttpDispatcher { @Override public int getOrder() { return DynamicPropertyFactory.getInstance().getIntProperty(KEY_ORDER, Integer.MAX_VALUE).get(); } @Override int getOrder(); @Override boolean enabled(); @Override void init(Router router); }### Answer: @Test public void getOrder() { Assert.assertEquals(Integer.MAX_VALUE, dispatcher.getOrder()); }
### Question: DefaultRegistryInitializer implements MetricsInitializer { @Override @SuppressWarnings("deprecation") public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { this.globalRegistry = globalRegistry; System.setProperty("spectator.api.gaugePollingFrequency", Duration.ofMillis(config.getMsPollInterval()).toString()); System.setProperty(SERVO_POLLERS, String.valueOf(config.getMsPollInterval())); registry = new com.netflix.spectator.servo.ServoRegistry(); globalRegistry.add(registry); } @Override int getOrder(); @Override @SuppressWarnings("deprecation") void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Override void destroy(); static final String SERVO_POLLERS; }### Answer: @Test @SuppressWarnings("deprecation") public void init() { registryInitializer.init(globalRegistry, new EventBus(), new MetricsBootstrapConfig()); Assert.assertEquals(-10, registryInitializer.getOrder()); Assert.assertThat(globalRegistry.getDefaultRegistry(), Matchers.instanceOf(com.netflix.spectator.servo.ServoRegistry.class)); Assert.assertEquals(1, registries.size()); Assert.assertEquals(1, DefaultMonitorRegistry.getInstance().getRegisteredMonitors().size()); registryInitializer.destroy(); Assert.assertEquals(0, registries.size()); Assert.assertEquals(0, DefaultMonitorRegistry.getInstance().getRegisteredMonitors().size()); }
### Question: VertxRestDispatcher extends AbstractVertxHttpDispatcher { protected void onRequest(RoutingContext context) { if (transport == null) { transport = SCBEngine.getInstance().getTransportManager().findTransport(Const.RESTFUL); microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); } HttpServletRequestEx requestEx = new VertxServerRequestToHttpServletRequest(context); HttpServletResponseEx responseEx = new VertxServerResponseToHttpServletResponse(context.response()); if (SCBEngine.getInstance().isFilterChainEnabled()) { InvocationCreator creator = new RestVertxProducerInvocationCreator(context, microserviceMeta, transport.getEndpoint(), requestEx, responseEx); new RestProducerInvocationFlow(creator, requestEx, responseEx) .run(); return; } VertxRestInvocation vertxRestInvocation = new VertxRestInvocation(); context.put(RestConst.REST_PRODUCER_INVOCATION, vertxRestInvocation); vertxRestInvocation.invoke(transport, requestEx, responseEx, httpServerFilters); } @Override int getOrder(); @Override boolean enabled(); @Override void init(Router router); }### Answer: @Test public void onRequest(@Mocked Vertx vertx, @Mocked Context context, @Mocked HttpServerRequest request, @Mocked SocketAddress socketAdrress) { Map<String, Object> map = new HashMap<>(); RoutingContext routingContext = new MockUp<RoutingContext>() { @Mock RoutingContext put(String key, Object obj) { map.put(key, obj); return null; } @Mock HttpServerRequest request() { return request; } }.getMockInstance(); new Expectations() { { Vertx.currentContext(); result = context; } }; Deencapsulation.invoke(dispatcher, "onRequest", routingContext); Assert.assertEquals(VertxRestInvocation.class, map.get(RestConst.REST_PRODUCER_INVOCATION).getClass()); Assert.assertTrue(invoked); }
### Question: VertxRestDispatcher extends AbstractVertxHttpDispatcher { String wrapResponseBody(String message) { if (isValidJson(message)) { return message; } JsonObject jsonObject = new JsonObject(); jsonObject.put("message", message); return jsonObject.toString(); } @Override int getOrder(); @Override boolean enabled(); @Override void init(Router router); }### Answer: @Test public void testWrapResponseBody() { VertxRestDispatcher vertxRestDispatcher = new VertxRestDispatcher(); String message = "abcd"; String bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"message\":\"abcd\"}", bodyString); message = "\"abcd\""; bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"message\":\"\\\"abcd\\\"\"}", bodyString); message = ".01ab\"!@#$%^&*()'\\cd"; bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"message\":\".01ab\\\"!@#$%^&*()'\\\\cd\"}", bodyString); message = new JsonObject().put("key", new JsonObject().put("k2", "value")).toString(); bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"key\":{\"k2\":\"value\"}}", bodyString); message = "ab\"23\n@!#cd"; bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"message\":\"ab\\\"23\\n@!#cd\"}", bodyString); message = "ab\"23\r\n@!#cd"; bodyString = vertxRestDispatcher.wrapResponseBody(message); Assert.assertNotNull(bodyString); Assert.assertEquals("{\"message\":\"ab\\\"23\\r\\n@!#cd\"}", bodyString); }
### Question: CseXmlWebApplicationContext extends XmlWebApplicationContext { @Override protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { super.invokeBeanFactoryPostProcessors(beanFactory); ServletUtils.init(getServletContext()); } CseXmlWebApplicationContext(); CseXmlWebApplicationContext(ServletContext servletContext); void setDefaultBeanResource(String[] defaultBeanResource); @Override String[] getConfigLocations(); }### Answer: @Test public void testInjectServlet(@Mocked ConfigurableListableBeanFactory beanFactory) { Holder<Boolean> holder = new Holder<>(); new MockUp<RestServletInjector>() { @Mock public Dynamic defaultInject(ServletContext servletContext) { holder.value = true; return null; } }; context.invokeBeanFactoryPostProcessors(beanFactory); Assert.assertTrue(holder.value); }
### Question: ServletUtils { static void checkUrlPattern(String urlPattern) { if (!urlPattern.startsWith("/")) { throw new ServiceCombException("only support rule like /* or /path/* or /path1/path2/* and so on."); } int idx = urlPattern.indexOf("/*"); if (idx < 0 || (idx >= 0 && idx != urlPattern.length() - 2)) { throw new ServiceCombException("only support rule like /* or /path/* or /path1/path2/* and so on."); } } static boolean canPublishEndpoint(String listenAddress); static void saveUrlPrefix(ServletContext servletContext); static void init(ServletContext servletContext); }### Answer: @Test public void testCheckUrlPatternNormal() { ServletUtils.checkUrlPattern("/*"); ServletUtils.checkUrlPattern("/abc/*"); ServletUtils.checkUrlPattern("/abc/def/*"); } @Test public void testCheckUrlPatternMiddleWideChar() { try { ServletUtils.checkUrlPattern("/abc/*def"); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals("only support rule like /* or /path/* or /path1/path2/* and so on.", e.getMessage()); } } @Test public void testCheckUrlPatternNoWideChar() { try { ServletUtils.checkUrlPattern("/abcdef"); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals("only support rule like /* or /path/* or /path1/path2/* and so on.", e.getMessage()); } } @Test public void testCheckUrlPatternNotStartWithSlash() { try { ServletUtils.checkUrlPattern("abcdef/*"); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals("only support rule like /* or /path/* or /path1/path2/* and so on.", e.getMessage()); } }
### Question: DefaultRegistryInitializer implements MetricsInitializer { @Override public void destroy() { if (registry != null) { DefaultMonitorRegistry.getInstance().unregister(registry); globalRegistry.remove(registry); } } @Override int getOrder(); @Override @SuppressWarnings("deprecation") void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Override void destroy(); static final String SERVO_POLLERS; }### Answer: @Test public void destroy_notInit() { registryInitializer.destroy(); }
### Question: ServletUtils { static String[] filterUrlPatterns(String... urlPatterns) { return filterUrlPatterns(Arrays.asList(urlPatterns)); } static boolean canPublishEndpoint(String listenAddress); static void saveUrlPrefix(ServletContext servletContext); static void init(ServletContext servletContext); }### Answer: @Test public void testFilterUrlPatternsNormal() { String urlPattern = "/r1/*"; Collection<String> urlPatterns = Arrays.asList(urlPattern); String[] result = ServletUtils.filterUrlPatterns(urlPatterns); Assert.assertThat(result, Matchers.arrayContaining("/r1/*")); result = ServletUtils.filterUrlPatterns(urlPattern); Assert.assertThat(result, Matchers.arrayContaining("/r1/*")); } @Test public void testFilterUrlPatternsEmpty() { Collection<String> urlPatterns = Arrays.asList(" ", "\t"); String[] result = ServletUtils.filterUrlPatterns(urlPatterns); Assert.assertThat(result, Matchers.emptyArray()); } @Test public void testFilterUrlPatternsInvalid() { Collection<String> urlPatterns = Arrays.asList("/abc"); try { ServletUtils.filterUrlPatterns(urlPatterns); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals("only support rule like /* or /path/* or /path1/path2/* and so on.", e.getMessage()); } }
### Question: ServletUtils { public static void saveUrlPrefix(ServletContext servletContext) { String urlPrefix = collectUrlPrefix(servletContext, RestServlet.class); if (urlPrefix == null) { LOGGER.info("RestServlet not found, will not save UrlPrefix."); return; } ClassLoaderScopeContext.setClassLoaderScopeProperty(DefinitionConst.URL_PREFIX, urlPrefix); LOGGER.info("UrlPrefix of this instance is \"{}\".", urlPrefix); } static boolean canPublishEndpoint(String listenAddress); static void saveUrlPrefix(ServletContext servletContext); static void init(ServletContext servletContext); }### Answer: @Test public void testSaveUrlPrefixNull(@Mocked ServletContext servletContext) { ClassLoaderScopeContext.clearClassLoaderScopeProperty(); ServletUtils.saveUrlPrefix(servletContext); Assert.assertNull(ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX)); ClassLoaderScopeContext.clearClassLoaderScopeProperty(); } @Test public void testSaveUrlPrefixNormal(@Mocked ServletContext servletContext, @Mocked ServletRegistration servletRegistration) { ClassLoaderScopeContext.clearClassLoaderScopeProperty(); new Expectations() { { servletContext.getContextPath(); result = "/root"; servletRegistration.getClassName(); result = RestServlet.class.getName(); servletRegistration.getMappings(); result = Arrays.asList("/rest/*"); servletContext.getServletRegistrations(); result = Collections.singletonMap("test", servletRegistration); } }; ServletUtils.saveUrlPrefix(servletContext); Assert.assertThat(ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX), Matchers.is("/root/rest")); ClassLoaderScopeContext.clearClassLoaderScopeProperty(); }
### Question: ServletUtils { static File createUploadDir(ServletContext servletContext, String location) { File dir = new File(location); if (!dir.isAbsolute()) { dir = new File((File) servletContext.getAttribute(ServletContext.TEMPDIR), location).getAbsoluteFile(); } if (!dir.exists()) { dir.mkdirs(); } return dir; } static boolean canPublishEndpoint(String listenAddress); static void saveUrlPrefix(ServletContext servletContext); static void init(ServletContext servletContext); }### Answer: @Test public void createUploadDir_relative(@Mocked ServletContext servletContext) throws IOException { File tempDir = Files.createTempDirectory("temp").toFile(); new Expectations() { { servletContext.getAttribute(ServletContext.TEMPDIR); result = tempDir; } }; File expectDir = new File(tempDir, "upload"); Assert.assertFalse(expectDir.exists()); File dir = ServletUtils.createUploadDir(servletContext, "upload"); Assert.assertTrue(expectDir.exists()); Assert.assertEquals(expectDir.getAbsolutePath(), dir.getAbsolutePath()); dir.delete(); Assert.assertFalse(expectDir.exists()); tempDir.delete(); Assert.assertFalse(tempDir.exists()); } @Test public void createUploadDir_absolute(@Mocked ServletContext servletContext) throws IOException { File tempDir = Files.createTempDirectory("temp").toFile(); File expectDir = new File(tempDir, "upload"); Assert.assertFalse(expectDir.exists()); File dir = ServletUtils.createUploadDir(servletContext, expectDir.getAbsolutePath()); Assert.assertTrue(expectDir.exists()); Assert.assertEquals(expectDir.getAbsolutePath(), dir.getAbsolutePath()); dir.delete(); Assert.assertFalse(expectDir.exists()); tempDir.delete(); Assert.assertFalse(tempDir.exists()); }
### Question: RestAsyncListener implements AsyncListener { @Override public void onTimeout(AsyncEvent event) throws IOException { ServletRequest request = event.getSuppliedRequest(); HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST); LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI()); synchronized (requestEx) { ServletResponse response = event.getAsyncContext().getResponse(); if (!response.isCommitted()) { response.setContentType(MediaType.APPLICATION_JSON); ((HttpServletResponse) response).setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode()); PrintWriter out = response.getWriter(); out.write(TIMEOUT_MESSAGE); response.flushBuffer(); } request.removeAttribute(RestConst.REST_REQUEST); } LOGGER.error("Rest request timeout committed, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI()); } @Override void onComplete(AsyncEvent event); @Override void onTimeout(AsyncEvent event); @Override void onError(AsyncEvent event); @Override void onStartAsync(AsyncEvent event); }### Answer: @Test public void onTimeoutCommitted() throws IOException { committed = true; listener.onTimeout(event); Assert.assertNull(request.getAttribute(RestConst.REST_REQUEST)); Assert.assertFalse(flushed); } @Test public void onTimeoutNotCommitted() throws IOException { committed = false; listener.onTimeout(event); Assert.assertNull(request.getAttribute(RestConst.REST_REQUEST)); Assert.assertEquals(MediaType.APPLICATION_JSON, contentType); Assert.assertEquals(500, statusCode); Assert.assertTrue(flushed); Assert.assertEquals("{\"message\":\"Timeout when processing the request.\"}", writer.toString()); }
### Question: RestServlet extends HttpServlet { @Override public void init() throws ServletException { super.init(); LOGGER.info("Rest Servlet inited"); } @Override void init(); @Override void service(final HttpServletRequest request, final HttpServletResponse response); }### Answer: @Test public void testInit() throws ServletException { restservlet.init(); Assert.assertTrue(true); }
### Question: RestServlet extends HttpServlet { @Override public void service(final HttpServletRequest request, final HttpServletResponse response) { servletRestServer.service(request, response); } @Override void init(); @Override void service(final HttpServletRequest request, final HttpServletResponse response); }### Answer: @Test public void testService() { Holder<Boolean> holder = new Holder<>(); ServletRestDispatcher servletRestServer = new MockUp<ServletRestDispatcher>() { @Mock void service(HttpServletRequest request, HttpServletResponse response) { holder.value = true; } }.getMockInstance(); Deencapsulation.setField(restservlet, "servletRestServer", servletRestServer); restservlet.service(null, null); Assert.assertTrue(holder.value); }
### Question: ServletRestTransport extends AbstractTransport { @Override public boolean init() { String urlPrefix = ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX); Map<String, String> queryMap = new HashMap<>(); if (!StringUtils.isEmpty(urlPrefix)) { queryMap.put(DefinitionConst.URL_PREFIX, urlPrefix); } String listenAddress = ServletConfig.getLocalServerAddress(); setListenAddressWithoutSchema(listenAddress, queryMap); restClient = RestTransportClientManager.INSTANCE.getRestClient(); return true; } @Override String getName(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testInitNotPublish(@Mocked RestTransportClient restTransportClient) { new MockUp<RestTransportClientManager>() { @Mock public RestTransportClient getRestTransportClient(boolean sslEnabled) { return restTransportClient; } }; new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = null; } }; Assert.assertTrue(transport.init()); Assert.assertNull(transport.getPublishEndpoint()); } @Test public void testInitPublishNoUrlPrefix(@Mocked RestTransportClient restTransportClient) { new MockUp<RestTransportClientManager>() { @Mock public RestTransportClient getRestTransportClient(boolean sslEnabled) { return restTransportClient; } }; new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = "1.1.1.1:1234"; } }; Assert.assertTrue(transport.init()); Assert.assertEquals("rest: } @Test public void testInitPublishWithUrlPrefix(@Mocked RestTransportClient restTransportClient) { new MockUp<RestTransportClientManager>() { @Mock public RestTransportClient getRestTransportClient(boolean sslEnabled) { return restTransportClient; } }; new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = "1.1.1.1:1234"; } }; ClassLoaderScopeContext.setClassLoaderScopeProperty(DefinitionConst.URL_PREFIX, "/root"); Assert.assertTrue(transport.init()); Assert.assertEquals("rest: }
### Question: ServletRestTransport extends AbstractTransport { @Override public boolean canInit() { String listenAddress = ServletConfig.getLocalServerAddress(); if (listenAddress == null) { return true; } if (!ServletUtils.canPublishEndpoint(listenAddress)) { LOGGER.info("ignore transport {}.", this.getClass().getName()); return false; } return true; } @Override String getName(); @Override boolean canInit(); @Override boolean init(); @Override void send(Invocation invocation, AsyncResponse asyncResp); }### Answer: @Test public void testCanInitNullAddress() throws IOException { new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = null; } }; ServletRestTransport transport = new ServletRestTransport(); Assert.assertTrue(transport.canInit()); } @Test public void testCanInitListened() throws IOException { ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = "0.0.0.0:" + port; } }; ServletRestTransport transport = new ServletRestTransport(); Assert.assertTrue(transport.canInit()); ss.close(); } @Test public void testCanInitNotListened() throws IOException { ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); ss.close(); new Expectations(ServletConfig.class) { { ServletConfig.getLocalServerAddress(); result = "0.0.0.0:" + port; } }; ServletRestTransport transport = new ServletRestTransport(); Assert.assertFalse(transport.canInit()); }
### Question: RestServletInjector { public static Dynamic defaultInject(ServletContext servletContext) { RestServletInjector injector = new RestServletInjector(); String urlPattern = ServletConfig.getServletUrlPattern(); return injector.inject(servletContext, urlPattern); } static Dynamic defaultInject(ServletContext servletContext); Dynamic inject(ServletContext servletContext, String urlPattern); static final String SERVLET_NAME; }### Answer: @Test public void testDefaultInjectEmptyUrlPattern(@Mocked ServletContext servletContext, @Mocked Dynamic dynamic) { new Expectations(ServletConfig.class) { { ServletConfig.getServletUrlPattern(); result = null; } }; Assert.assertEquals(null, RestServletInjector.defaultInject(servletContext)); } @Test public void testDefaultInjectNotListen(@Mocked ServletContext servletContext, @Mocked Dynamic dynamic) throws UnknownHostException, IOException { try (ServerSocket ss = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"))) { int port = ss.getLocalPort(); new Expectations(ServletConfig.class) { { ServletConfig.getServletUrlPattern(); result = "/*"; ServletConfig.getLocalServerAddress(); result = "127.0.0.1:" + port; } }; } Assert.assertEquals(null, RestServletInjector.defaultInject(servletContext)); } @Test public void testDefaultInjectListen(@Mocked ServletContext servletContext, @Mocked Dynamic dynamic) throws UnknownHostException, IOException { try (ServerSocket ss = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"))) { int port = ss.getLocalPort(); new Expectations(ServletConfig.class) { { ServletConfig.getServletUrlPattern(); result = "/rest/*"; ServletConfig.getLocalServerAddress(); result = "127.0.0.1:" + port; } }; Assert.assertEquals(dynamic, RestServletInjector.defaultInject(servletContext)); } }
### Question: RestServletProducerInvocation extends RestProducerInvocation { @Override protected void findRestOperation() { super.findRestOperation(); boolean cacheRequest = collectCacheRequest(restOperationMeta.getOperationMeta()); ((StandardHttpServletRequestEx) requestEx).setCacheRequest(cacheRequest); } }### Answer: @Test public void findRestOperationCacheTrue(@Mocked HttpServletRequest request, @Mocked HttpServerFilter f1) { HttpServletRequestEx requestEx = new StandardHttpServletRequestEx(request); Deencapsulation.setField(restInvocation, "requestEx", requestEx); new MockUp<RestProducerInvocation>() { @Mock void findRestOperation() { Deencapsulation.setField(getMockInstance(), "restOperationMeta", restOperationMeta); } }; List<HttpServerFilter> httpServerFilters = Arrays.asList(f1); new Expectations() { { f1.needCacheRequest(operationMeta); result = true; } }; restInvocation.setHttpServerFilters(httpServerFilters); restInvocation.findRestOperation(); Assert.assertTrue(Deencapsulation.getField(requestEx, "cacheRequest")); }
### Question: RestServletProducerInvocation extends RestProducerInvocation { protected boolean collectCacheRequest(OperationMeta operationMeta) { for (HttpServerFilter filter : httpServerFilters) { if (filter.needCacheRequest(operationMeta)) { return true; } } return false; } }### Answer: @Test public void collectCacheRequestCacheTrue(@Mocked HttpServerFilter f1) { List<HttpServerFilter> httpServerFilters = Arrays.asList(f1); new Expectations() { { f1.needCacheRequest(operationMeta); result = true; } }; restInvocation.setHttpServerFilters(httpServerFilters); Assert.assertTrue(restInvocation.collectCacheRequest(operationMeta)); } @Test public void collectCacheRequestCacheFalse(@Mocked HttpServerFilter f1) { List<HttpServerFilter> httpServerFilters = Arrays.asList(f1); new Expectations() { { f1.needCacheRequest(operationMeta); result = false; } }; restInvocation.setHttpServerFilters(httpServerFilters); Assert.assertFalse(restInvocation.collectCacheRequest(operationMeta)); }
### Question: ServletRestDispatcher { public void service(HttpServletRequest request, HttpServletResponse response) { if (transport == null) { transport = SCBEngine.getInstance().getTransportManager().findTransport(Const.RESTFUL); microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); } AsyncContext asyncCtx = request.startAsync(); asyncCtx.addListener(restAsyncListener); asyncCtx.setTimeout(ServletConfig.getAsyncServletTimeout()); HttpServletRequestEx requestEx = new StandardHttpServletRequestEx(request); HttpServletResponseEx responseEx = new StandardHttpServletResponseEx(response); if (SCBEngine.getInstance().isFilterChainEnabled()) { ((StandardHttpServletRequestEx) requestEx).setCacheRequest(true); InvocationCreator creator = new RestServletProducerInvocationCreator(microserviceMeta, transport.getEndpoint(), requestEx, responseEx); new RestProducerInvocationFlow(creator, requestEx, responseEx) .run(); return; } RestServletProducerInvocation restProducerInvocation = new RestServletProducerInvocation(); restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters); } void service(HttpServletRequest request, HttpServletResponse response); }### Answer: @Test public void service() { Holder<Boolean> handled = new Holder<>(); new MockUp<RestServletProducerInvocation>() { @Mock void invoke(Transport transport, HttpServletRequestEx requestEx, HttpServletResponseEx responseEx, List<HttpServerFilter> httpServerFilters) { handled.value = true; } }; dispatcher.service(request, response); Assert.assertTrue(handled.value); }
### Question: RestServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { try { initSpring(sce); } catch (Exception e) { throw new Error(e); } } @Override void contextInitialized(ServletContextEvent sce); AbstractApplicationContext initSpring(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); }### Answer: @Test public void testcontextInitializedException() { boolean status = true; RestServletContextListener listener = new RestServletContextListener(); ServletContextEvent sce = Mockito.mock(ServletContextEvent.class); try { listener.contextInitialized(sce); } catch (Exception | Error e) { status = false; } Assert.assertFalse(status); }
### Question: RestServletContextListener implements ServletContextListener { public AbstractApplicationContext initSpring(ServletContextEvent sce) { context = new CseXmlWebApplicationContext(sce.getServletContext()); context.refresh(); return context; } @Override void contextInitialized(ServletContextEvent sce); AbstractApplicationContext initSpring(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); }### Answer: @Test public void testInitSpring() { boolean status = true; RestServletContextListener listener = new RestServletContextListener(); ServletContextEvent sce = Mockito.mock(ServletContextEvent.class); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(sce.getServletContext()).thenReturn(context); Mockito.when(sce.getServletContext().getInitParameter("contextConfigLocation")).thenReturn("locations"); try { listener.initSpring(sce); } catch (Exception e) { status = false; } Assert.assertFalse(status); }
### Question: ServletConfig { public static String getLocalServerAddress() { DynamicStringProperty address = DynamicPropertyFactory.getInstance().getStringProperty(SERVICECOMB_REST_ADDRESS, null); return address.get(); } private ServletConfig(); static long getAsyncServletTimeout(); static String getLocalServerAddress(); static String getServletUrlPattern(); static final long DEFAULT_ASYN_SERVLET_TIMEOUT; static final String KEY_SERVLET_URL_PATTERN; static final String SERVICECOMB_REST_ADDRESS; static final String KEY_SERVICECOMB_ASYC_SERVLET_TIMEOUT; static final String DEFAULT_URL_PATTERN; }### Answer: @Test public void testGetLocalServerAddress() { Assert.assertNull(ServletConfig.getLocalServerAddress()); }
### Question: ServletConfig { public static long getAsyncServletTimeout() { return asyncServletTimeoutProperty.get(); } private ServletConfig(); static long getAsyncServletTimeout(); static String getLocalServerAddress(); static String getServletUrlPattern(); static final long DEFAULT_ASYN_SERVLET_TIMEOUT; static final String KEY_SERVLET_URL_PATTERN; static final String SERVICECOMB_REST_ADDRESS; static final String KEY_SERVICECOMB_ASYC_SERVLET_TIMEOUT; static final String DEFAULT_URL_PATTERN; }### Answer: @Test public void testGetServerTimeout() { Assert.assertEquals(ServletConfig.DEFAULT_ASYN_SERVLET_TIMEOUT, ServletConfig.getAsyncServletTimeout()); }