Search in sources :

Example 36 with Holder

use of org.apache.servicecomb.foundation.common.Holder in project incubator-servicecomb-java-chassis by apache.

the class TestCseClientHttpRequest method testNormal.

@Test
public void testNormal() {
    Holder<Invocation> holder = new Holder<>();
    CseClientHttpRequest client = new CseClientHttpRequest(URI.create("cse://defaultMicroservice/" + SpringmvcImpl.class.getSimpleName() + "/bytes"), HttpMethod.POST) {

        /**
         * {@inheritDoc}
         */
        @Override
        protected Response doInvoke(Invocation invocation) {
            holder.value = invocation;
            return Response.ok("result");
        }
    };
    byte[] body = "abc".getBytes();
    HttpHeaders headers = new HttpHeaders();
    headers.add("token", "123");
    client.setRequestBody(body);
    client.setHttpHeaders(headers);
    client.execute();
    Assert.assertArrayEquals(body, (byte[]) holder.value.getInvocationArguments().get("input"));
    Assert.assertEquals("123", holder.value.getInvocationArguments().get("token"));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Invocation(org.apache.servicecomb.core.Invocation) Holder(org.apache.servicecomb.foundation.common.Holder) Test(org.junit.Test)

Example 37 with Holder

use of org.apache.servicecomb.foundation.common.Holder in project incubator-servicecomb-java-chassis by apache.

the class TestRestServerVerticle method mountGlobalRestFailureHandler.

@Test
public void mountGlobalRestFailureHandler() {
    Router mainRouter = Mockito.mock(Router.class);
    Holder<Handler<RoutingContext>> handlerHolder = new Holder<>();
    Holder<Route> routeHolder = new Holder<>();
    Route route = new MockUp<Route>() {

        @Mock
        Route failureHandler(Handler<RoutingContext> failureHandler) {
            handlerHolder.value = failureHandler;
            return null;
        }

        @Mock
        Route handler(io.vertx.core.Handler<io.vertx.ext.web.RoutingContext> requestHandler) {
            return routeHolder.value;
        }
    }.getMockInstance();
    routeHolder.value = route;
    Mockito.when(mainRouter.route()).thenReturn(route);
    RestServerVerticle restServerVerticle = new RestServerVerticle();
    Deencapsulation.invoke(restServerVerticle, "mountGlobalRestFailureHandler", mainRouter);
    Assert.assertNotNull(handlerHolder.value);
    RoutingContext routingContext = Mockito.mock(RoutingContext.class);
    HttpServerResponse response = Mockito.mock(HttpServerResponse.class);
    Mockito.when(response.setStatusCode(500)).thenReturn(response);
    Mockito.when(response.putHeader("Content-Type", "application/json")).thenReturn(response);
    Mockito.when(routingContext.response()).thenReturn(response);
    handlerHolder.value.handle(routingContext);
    Mockito.verify(response).end("{\"message\":\"unknown error\"}");
}
Also used : RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) Holder(org.apache.servicecomb.foundation.common.Holder) Router(io.vertx.ext.web.Router) Handler(io.vertx.core.Handler) CorsHandler(io.vertx.ext.web.handler.CorsHandler) Mock(mockit.Mock) RoutingContext(io.vertx.ext.web.RoutingContext) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Route(io.vertx.ext.web.Route) Test(org.junit.Test)

Example 38 with Holder

use of org.apache.servicecomb.foundation.common.Holder in project incubator-servicecomb-java-chassis by apache.

the class TestGeneric method testHolderUser_rest.

@SuppressWarnings("unchecked")
private void testHolderUser_rest() {
    Holder<User> holder = new Holder<>(new User());
    Holder<User> result = intf.testHolderUser(holder);
    TestMgr.check("{\"name\":\"nameA\",\"age\":100,\"index\":0,\"names\":null}", result.value.jsonString());
    result = restTemplate.postForObject(prefix + "/holderUser", holder, Holder.class);
    TestMgr.check("{\"name\":\"nameA\",\"age\":100,\"index\":0,\"names\":null}", result.value.jsonString());
}
Also used : User(org.apache.servicecomb.demo.server.User) Holder(org.apache.servicecomb.foundation.common.Holder)

Example 39 with Holder

use of org.apache.servicecomb.foundation.common.Holder in project incubator-servicecomb-java-chassis by apache.

the class TestLoadBalanceHandler2 method testIsolationEventWithEndpoint.

@Test
public void testIsolationEventWithEndpoint() throws Exception {
    ReferenceConfig referenceConfig = Mockito.mock(ReferenceConfig.class);
    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
    InvocationRuntimeType invocationRuntimeType = Mockito.mock(InvocationRuntimeType.class);
    SchemaMeta schemaMeta = Mockito.mock(SchemaMeta.class);
    when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
    MicroserviceMeta microserviceMeta = Mockito.mock(MicroserviceMeta.class);
    when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
    when(schemaMeta.getMicroserviceName()).thenReturn("testMicroserviceName");
    when(microserviceMeta.getAppId()).thenReturn("testApp");
    when(referenceConfig.getVersionRule()).thenReturn("0.0.0+");
    when(referenceConfig.getTransport()).thenReturn("rest");
    Invocation invocation = new Invocation(referenceConfig, operationMeta, invocationRuntimeType, new HashMap<>());
    InstanceCacheManager instanceCacheManager = Mockito.mock(InstanceCacheManager.class);
    TransportManager transportManager = Mockito.mock(TransportManager.class);
    Transport transport = Mockito.mock(Transport.class);
    ArchaiusUtils.setProperty("servicecomb.loadbalance.filter.operation.enabled", "false");
    // set up data
    MicroserviceInstance myself = new MicroserviceInstance();
    DataCenterInfo info = new DataCenterInfo();
    info.setName("test");
    info.setRegion("test");
    info.setAvailableZone("test");
    myself.setDataCenterInfo(info);
    MicroserviceInstance instance = new MicroserviceInstance();
    info = new DataCenterInfo();
    info.setName("test");
    info.setRegion("test");
    info.setAvailableZone("test");
    List<String> allMatchEndpoint = new ArrayList<>();
    allMatchEndpoint.add("rest://localhost:9090");
    instance.setEndpoints(allMatchEndpoint);
    instance.setDataCenterInfo(info);
    instance.setInstanceId("instance");
    Map<String, MicroserviceInstance> data = new HashMap<>();
    DiscoveryTreeNode parent = new DiscoveryTreeNode().name("parent").data(data);
    scbEngine.setTransportManager(transportManager);
    LocalRegistryStore.INSTANCE.initSelfWithMocked(null, myself);
    mockUpInstanceCacheManager(instanceCacheManager);
    when(instanceCacheManager.getOrCreateVersionedCache("testApp", "testMicroserviceName", "0.0.0+")).thenReturn(parent);
    when(transportManager.findTransport("rest")).thenReturn(transport);
    LoadbalanceHandler handler = null;
    LoadBalancer loadBalancer = null;
    ServiceCombServer server = null;
    handler = new LoadbalanceHandler();
    loadBalancer = handler.getOrCreateLoadBalancer(invocation);
    server = loadBalancer.chooseServer(invocation);
    Assert.assertNull(server);
    data.put("instance", instance);
    parent.cacheVersion(parent.cacheVersion() + 1);
    loadBalancer = handler.getOrCreateLoadBalancer(invocation);
    server = loadBalancer.chooseServer(invocation);
    Assert.assertEquals("rest://localhost:9090", server.getEndpoint().getEndpoint());
    ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    ServiceCombLoadBalancerStats.INSTANCE.markFailure(server);
    // if errorThresholdPercentage greater than 0, it will activate.
    ArchaiusUtils.setProperty("servicecomb.loadbalance.isolation.errorThresholdPercentage", "10");
    ArchaiusUtils.setProperty("servicecomb.loadbalance.isolation.minIsolationTime", "10");
    Holder<Integer> count = new Holder<>(0);
    IsolationEndpointListener isolationEndpointListener = new IsolationEndpointListener(count);
    EventManager.getEventBus().register(isolationEndpointListener);
    Assert.assertEquals(0, count.value.intValue());
    loadBalancer = handler.getOrCreateLoadBalancer(invocation);
    server = loadBalancer.chooseServer(invocation);
    // no server is available
    Assert.assertNull(server);
    Assert.assertEquals(1, count.value.intValue());
    EventManager.unregister(isolationEndpointListener);
}
Also used : NonSwaggerInvocation(org.apache.servicecomb.core.NonSwaggerInvocation) Invocation(org.apache.servicecomb.core.Invocation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) DataCenterInfo(org.apache.servicecomb.registry.api.registry.DataCenterInfo) DiscoveryTreeNode(org.apache.servicecomb.registry.discovery.DiscoveryTreeNode) ReferenceConfig(org.apache.servicecomb.core.provider.consumer.ReferenceConfig) Holder(org.apache.servicecomb.foundation.common.Holder) InstanceCacheManager(org.apache.servicecomb.registry.cache.InstanceCacheManager) SchemaMeta(org.apache.servicecomb.core.definition.SchemaMeta) MicroserviceMeta(org.apache.servicecomb.core.definition.MicroserviceMeta) InvocationRuntimeType(org.apache.servicecomb.core.definition.InvocationRuntimeType) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) TransportManager(org.apache.servicecomb.core.transport.TransportManager) Transport(org.apache.servicecomb.core.Transport) Test(org.junit.Test)

Example 40 with Holder

use of org.apache.servicecomb.foundation.common.Holder in project incubator-servicecomb-java-chassis by apache.

the class TestLoadbalanceHandler method send_success.

@Test
public void send_success(@Injectable LoadBalancer loadBalancer) {
    MicroserviceInstance instance1 = new MicroserviceInstance();
    instance1.setInstanceId("1234");
    CacheEndpoint cacheEndpoint = new CacheEndpoint("rest://localhost:8080", instance1);
    ServiceCombServer server = new ServiceCombServer(null, restTransport, cacheEndpoint);
    LoadBalancerStats stats = new LoadBalancerStats("test");
    new Expectations(loadBalancer) {

        {
            loadBalancer.chooseServer(invocation);
            result = server;
            loadBalancer.getLoadBalancerStats();
            result = stats;
        }
    };
    sendResponse = Response.ok("success");
    Holder<String> result = new Holder<>();
    Deencapsulation.invoke(handler, "send", invocation, (AsyncResponse) resp -> {
        result.value = resp.getResult();
    }, loadBalancer);
    Assert.assertEquals(1, loadBalancer.getLoadBalancerStats().getSingleServerStat(server).getActiveRequestsCount());
    Assert.assertEquals("success", result.value);
}
Also used : Expectations(mockit.Expectations) SCBEngine(org.apache.servicecomb.core.SCBEngine) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) Transport(org.apache.servicecomb.core.Transport) Expectations(mockit.Expectations) CacheEndpoint(org.apache.servicecomb.registry.cache.CacheEndpoint) DiscoveryFilter(org.apache.servicecomb.registry.discovery.DiscoveryFilter) SPIServiceUtils(org.apache.servicecomb.foundation.common.utils.SPIServiceUtils) ArchaiusUtils(org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) ArrayList(java.util.ArrayList) SocketException(java.net.SocketException) Map(java.util.Map) After(org.junit.After) Mock(mockit.Mock) SCBBootstrap(org.apache.servicecomb.core.bootstrap.SCBBootstrap) Status(javax.ws.rs.core.Response.Status) Response(org.apache.servicecomb.swagger.invocation.Response) ExpectedException(org.junit.rules.ExpectedException) ExecutorService(java.util.concurrent.ExecutorService) LoadBalancerStats(com.netflix.loadbalancer.LoadBalancerStats) Before(org.junit.Before) MockUp(mockit.MockUp) InstanceCacheManager(org.apache.servicecomb.registry.cache.InstanceCacheManager) ConfigUtil(org.apache.servicecomb.config.ConfigUtil) Matchers(org.hamcrest.Matchers) Holder(org.apache.servicecomb.foundation.common.Holder) Test(org.junit.Test) Deencapsulation(mockit.Deencapsulation) Invocation(org.apache.servicecomb.core.Invocation) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Rule(org.junit.Rule) TransportManager(org.apache.servicecomb.core.transport.TransportManager) Injectable(mockit.Injectable) Assert(org.junit.Assert) Collections(java.util.Collections) Mocked(mockit.Mocked) CacheEndpoint(org.apache.servicecomb.registry.cache.CacheEndpoint) Holder(org.apache.servicecomb.foundation.common.Holder) LoadBalancerStats(com.netflix.loadbalancer.LoadBalancerStats) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) Test(org.junit.Test)

Aggregations

Holder (org.apache.servicecomb.foundation.common.Holder)108 Test (org.junit.Test)88 MockUp (mockit.MockUp)36 AtomicLong (java.util.concurrent.atomic.AtomicLong)28 Invocation (org.apache.servicecomb.core.Invocation)24 Expectations (mockit.Expectations)22 Vertx (io.vertx.core.Vertx)20 List (java.util.List)18 Response (org.apache.servicecomb.swagger.invocation.Response)18 Mock (mockit.Mock)16 HttpServerFilterBaseForTest (org.apache.servicecomb.common.rest.filter.HttpServerFilterBaseForTest)16 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 SCBEngine (org.apache.servicecomb.core.SCBEngine)14 ExpectedException (org.junit.rules.ExpectedException)14 CountDownLatch (java.util.concurrent.CountDownLatch)12 Status (javax.ws.rs.core.Response.Status)12 Deencapsulation (mockit.Deencapsulation)12 Mocked (mockit.Mocked)12 ConfigUtil (org.apache.servicecomb.config.ConfigUtil)12