diff options
author | 2017-07-25 15:18:33 +0800 | |
---|---|---|
committer | 2017-07-25 18:11:59 +0800 | |
commit | 672f3d40be83d9e380fd7be4b674d5e8d5fa36de (patch) | |
tree | 43105e1d5e2ba8e8accea8648e57e1cf87db3f00 /apiroute/apiroute-service/src/test | |
parent | 41d3db15a8e1a0496f9c2a5e15db2998a32bb9bf (diff) |
Divide the MSB source codes into two repos
Change-Id: Ie76d545b214a8ce5191f215350a623e1529983d9
Issue-id: MSB-5
Signed-off-by: HuabingZhao <zhao.huabing@zte.com.cn>
Diffstat (limited to 'apiroute/apiroute-service/src/test')
51 files changed, 5858 insertions, 0 deletions
diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java new file mode 100644 index 0000000..668d445 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java @@ -0,0 +1,56 @@ +package org.onap.msb.apiroute; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.msb.apiroute.SyncDataManager; +import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.fasterxml.jackson.core.type.TypeReference; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Http.class }) +@PowerMockIgnore({ "javax.net.ssl.*" }) +public class SyncDataManagerTest { + + @SuppressWarnings("unchecked") + @Before + public void setUpBeforeTest() { + Http http = PowerMockito.mock(Http.class); + + PowerMockito + .doNothing() + .when(http) + .asyncGet(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + PowerMockito + .doNothing() + .when(http) + .asyncGetDelayHandle(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + } + + @Test + public void testSyncDataManager() + { + SyncDataManager.initSyncTask("127.0.0.1",8500); + SyncDataManager.startWatchService("huangleibo"); + SyncDataManager.resetIndex("huangleibo"); + SyncDataManager.stopWatchService("huangleibo"); + SyncDataManager.stopWatchServiceList(); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java new file mode 100644 index 0000000..1048ce0 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java @@ -0,0 +1,69 @@ +package org.onap.msb.apiroute.health; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.msb.apiroute.health.ApiRouteHealthCheck; +import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.codahale.metrics.health.HealthCheck.Result; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpClientUtil.class }) +public class ApiRouteHealthCheckTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(ApiRouteHealthCheckTest.class); + + @Test + public void testchecksuccess() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ApiRouteHealthCheck check = new ApiRouteHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ApiRouteHealthCheck check = new ApiRouteHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testcheckfailed health"); + } + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java new file mode 100644 index 0000000..50ac829 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java @@ -0,0 +1,103 @@ +package org.onap.msb.apiroute.health; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.msb.apiroute.health.ConsulLinkHealthCheck; +import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.codahale.metrics.health.HealthCheck.Result; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpClientUtil.class,ConsulLinkHealthCheck.class }) +public class ConsulLinkHealthCheckTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(ConsulLinkHealthCheckTest.class); + + @Test + public void testchecksuccess() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug("testcheckfailed health"); + } + } + + + @Test + public void testcheckNoENV() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn(""); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckNoENV health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug("testcheckNoENV health"); + } + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java new file mode 100644 index 0000000..810f645 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java @@ -0,0 +1,77 @@ +package org.onap.msb.apiroute.health; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.msb.apiroute.health.OpenRestyHealthCheck; +import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.codahale.metrics.health.HealthCheck.Result; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ HttpClientUtil.class,OpenRestyHealthCheck.class }) +public class OpenRestyHealthCheckTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(OpenRestyHealthCheckTest.class); + + @Test + public void testchecksuccess() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn("10080"); + + OpenRestyHealthCheck check = new OpenRestyHealthCheck(); + + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() + { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn(""); + + OpenRestyHealthCheck check = new OpenRestyHealthCheck(); + + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testchecksuccess health"); + } + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java new file mode 100644 index 0000000..a667df2 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java @@ -0,0 +1,77 @@ +package org.onap.msb.apiroute.health; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.health.RedisHealthCheck; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.codahale.metrics.health.HealthCheck.Result; +import com.fiftyonred.mock_jedis.MockJedisPool; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class RedisHealthCheckTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(RedisHealthCheckTest.class); + + @Before + public void setUpBeforeTest() throws Exception { + + } + + @SuppressWarnings("static-access") + @Test + public void testchecksuccess() + { + + try { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + RedisHealthCheck check = new RedisHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug(" testchecksuccess health"); + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testcheckfailed() + { + RedisHealthCheck check = new RedisHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); + } + else + { + LOGGER.debug("testcheckfailed health"); + } + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java new file mode 100644 index 0000000..bb90a2c --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java @@ -0,0 +1,252 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.ApiRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; +import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class ApiRouteServiceWrapperTest { + private static ApiRouteServiceWrapper apiRouteServiceWrapper; + private static Comparator<ApiRouteInfo> apiRouteComparator = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + apiRouteServiceWrapper=ApiRouteServiceWrapper.getInstance(); + apiRouteComparator = new Comparator<ApiRouteInfo>() { + @Override + public int compare(ApiRouteInfo o1, ApiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + if (!o1.getVersion().equals(o2.getVersion())) + return (o1.getVersion()).compareTo(o2.getVersion()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + + + @Test + public void test_getApiRouteInstance_not_exist(){ + try { + apiRouteServiceWrapper.getApiRouteInstance("testForJunit", "v1","","","ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_getApiRouteInstance(){ + + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals(apirouteInfo,dbApirouteInfo ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + + @Test + public void test_getAllApiRouteInstances(){ + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); + List<ApiRouteInfo> expected = new ArrayList<>(); + expected.add(apirouteInfo); + expected.add(apirouteInfo2); + Collections.sort(expected, apiRouteComparator); + + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); + + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); + List<ApiRouteInfo> apiRouterList=apiRouteServiceWrapper.getAllApiRouteInstances("ip"); + Collections.sort(apiRouterList, apiRouteComparator); + + Assert.assertEquals(expected,apiRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_updateApiRouteStatus(){ + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals("1",dbApirouteInfo.getStatus() ); + apiRouteServiceWrapper.updateApiRouteStatus("testapi","v1","","","0", "ip"); + dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals("0",dbApirouteInfo.getStatus() ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + + @Test + public void test_deleteApiRoute(){ + ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); + ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi2", "null","","","ip"); + Assert.assertNotNull(dbApirouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + apiRouteServiceWrapper.deleteApiRoute("testapi2", "null","","","ip"); + apiRouteServiceWrapper.getApiRouteInstance("testapi2", "","","","ip"); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } + + @Test + public void test_getAllApiDocs(){ + String[] paths=apiRouteServiceWrapper.getAllApiDocs(); + String[] expecteds_paths={"api-doc1.json","api-doc2.json"}; + Arrays.sort(expecteds_paths); + Arrays.sort(paths); + Assert.assertArrayEquals(expecteds_paths, paths); + } + + @Test + public void test_getAllrouteByJson(){ + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + + ApiRouteInfo[] apirouteList={apirouteInfo}; + String expected_routeJson=JacksonJsonUtil.beanToJson(apirouteList); + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")).thenReturn("msb:routing:custom:*"); + + String allrouteJson= apiRouteServiceWrapper.getAllrouteByJson("ip"); + Assert.assertEquals(expected_routeJson, allrouteJson); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + + } + + + + private ApiRouteInfo buildApiRouteInfo(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + apirouteInfo.setServers(servers); + return apirouteInfo; + } + + private ApiRouteInfo buildApiRouteInfo2(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi2"); + apirouteInfo.setVersion(""); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi2/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("1"); + apirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; + apirouteInfo.setServers(servers); + return apirouteInfo; + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java new file mode 100644 index 0000000..3c77dbf --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java @@ -0,0 +1,208 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.CustomRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; +import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class CustomRouteServiceWrapperTest { + + private static CustomRouteServiceWrapper customRouteServiceWrapper; + private static Comparator<CustomRouteInfo> customRouteComparator = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + customRouteServiceWrapper=CustomRouteServiceWrapper.getInstance(); + customRouteComparator = new Comparator<CustomRouteInfo>() { + @Override + public int compare(CustomRouteInfo o1, CustomRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_getCustomRouteInstance_not_exist(){ + try { + customRouteServiceWrapper.getCustomRouteInstance("/testForJunit","","","ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + + } + + @Test + public void test_getCustomRouteInstance(){ + + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); + CustomRouteInfo dbCustomRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals(customrouteInfo,dbCustomRouteInfo ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_getAllCustomRouteInstances(){ + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); + List<CustomRouteInfo> expected = new ArrayList<>(); + expected.add(customrouteInfo); + expected.add(customrouteInfo2); + Collections.sort(expected, customRouteComparator); + + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")).thenReturn("msb:routing:custom:*"); + List<CustomRouteInfo> customRouterList=customRouteServiceWrapper.getAllCustomRouteInstances("ip"); + Collections.sort(customRouterList, customRouteComparator); + + Assert.assertEquals(expected,customRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_updateCustomRouteStatus(){ + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); + CustomRouteInfo dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals("1",dbCustomrouteInfo.getStatus() ); + customRouteServiceWrapper.updateCustomRouteStatus("/testcustom","","","0", "ip"); + dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals("0",dbCustomrouteInfo.getStatus() ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + + @Test + public void test_deleteCustomRoute(){ + CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); + CustomRouteInfo dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom2","","","ip"); + Assert.assertNotNull(dbCustomrouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + customRouteServiceWrapper.deleteCustomRoute("/testcustom2","","","ip"); + customRouteServiceWrapper.getCustomRouteInstance("/testcustom2","","","ip"); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } + + + private CustomRouteInfo buildCustomRouteInfo(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("/testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + return customrouteInfo; + } + + private CustomRouteInfo buildCustomRouteInfo2(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("/testcustom2"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("1"); + customrouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; + customrouteInfo.setServers(servers); + return customrouteInfo; + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java new file mode 100644 index 0000000..7c183dd --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java @@ -0,0 +1,241 @@ +package org.onap.msb.apiroute.wrapper; + +import io.dropwizard.jetty.HttpConnectorFactory; +import io.dropwizard.server.SimpleServerFactory; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.msb.apiroute.ApiRouteAppConfig; +import org.onap.msb.apiroute.api.ApiRouteInfo; +import org.onap.msb.apiroute.api.CustomRouteInfo; +import org.onap.msb.apiroute.api.DiscoverInfo; +import org.onap.msb.apiroute.api.IuiRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fiftyonred.mock_jedis.MockJedisPool; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JedisUtil.class, RedisAccessWrapper.class, ConfigUtil.class, + Http.class, InitRouteServiceWrapper.class }) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*" }) +public class InitRouteServiceWrapperTest { + private static InitRouteServiceWrapper initRouteServiceWrapper; + private static Consul consul; + + @SuppressWarnings("unchecked") + @BeforeClass + public static void setUpBeforeClass() throws Exception { + initRouteServiceWrapper = InitRouteServiceWrapper.getInstance(); + + Http http = PowerMockito.mock(Http.class); + + PowerMockito + .doNothing() + .when(http) + .asyncGet(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + PowerMockito + .doNothing() + .when(http) + .asyncGetDelayHandle(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + consul = Consul.builder().withHostAndPort("127.0.0.1", 8500).build(); + } + + @Before + public void initReidsMock() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool( + new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn( + mockJedisPool.getResource()); + + PowerMockito.replace( + PowerMockito.method(RedisAccessWrapper.class, "filterKeys")) + .with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, + Object[] args) throws Throwable { + return mockJedisPool.getResource().keys( + (String) args[0]); + } + }); + } + + @Test + public void test_startCheckRedisConnect() { + try { + boolean ifRedisConnect = initRouteServiceWrapper + .startCheckRedisConnect(); + Assert.assertEquals(true, ifRedisConnect); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + + } + } + + @Test + public void test_runConsulClientApp() { + + DiscoverInfo discoverInfo = new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.1"); + discoverInfo.setPort(10081); + + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + configuration.setDiscoverInfo(discoverInfo); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + + try { + initRouteServiceWrapper.runConsulClientApp(); + + ApiRouteInfo discoverApiService = new ApiRouteInfo(); + discoverApiService.setServiceName("msdiscover"); + discoverApiService.setUrl("/api/microservices/v1"); + discoverApiService.setVersion("v1"); + discoverApiService.setMetricsUrl("/admin/metrics"); + discoverApiService.setApiJson("/api/microservices/v1/swagger.json"); + discoverApiService.setHost("msb"); + + RouteServer[] servers = new RouteServer[1]; + servers[0] = new RouteServer(discoverInfo.getIp(), + String.valueOf(discoverInfo.getPort())); + discoverApiService.setServers(servers); + + ApiRouteInfo db_discoverApiService = ApiRouteServiceWrapper + .getInstance().getApiRouteInstance("msdiscover", "v1", + "msb", "", "ip"); + Assert.assertEquals(discoverApiService, db_discoverApiService); + + IuiRouteInfo discoverIUIService = new IuiRouteInfo(); + discoverIUIService.setServiceName("msdiscover"); + discoverIUIService.setUrl("/iui/microservices"); + discoverIUIService.setHost("msb"); + discoverIUIService.setServers(servers); + + Assert.assertEquals( + discoverIUIService, + IuiRouteServiceWrapper.getInstance().getIuiRouteInstance( + "msdiscover", "msb", "", "ip")); + + } catch (Exception e) { + assert false : "throw exception means error occured!" + + e.getMessage(); + } + } + + @Test + public void test_initRouteInfoFromJson() { + try { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("dwApp_server_connector_port")) + .thenReturn("8068"); + initRouteServiceWrapper.initRouteInfoFromJson(); + + ApiRouteInfo apiroute = new ApiRouteInfo(); + apiroute.setServiceName("microservices"); + apiroute.setUrl("/api/microservices/v1"); + apiroute.setVersion("v1"); + apiroute.setMetricsUrl("/admin/metrics"); + apiroute.setApiJson("/api/microservices/v1/swagger.json"); + apiroute.setHost("msb"); + apiroute.setControl("1"); + apiroute.setStatus("1"); + + RouteServer[] servers = new RouteServer[1]; + servers[0] = new RouteServer("127.0.0.1", "8068"); + apiroute.setServers(servers); + + ApiRouteInfo db_apiService = ApiRouteServiceWrapper + .getInstance() + .getApiRouteInstance("microservices", "v1", "msb", "", "ip"); + Assert.assertEquals(apiroute, db_apiService); + + IuiRouteInfo iuiRoute = new IuiRouteInfo(); + iuiRoute.setServiceName("microservices"); + iuiRoute.setUrl("/iui/microservices"); + iuiRoute.setHost("msb"); + iuiRoute.setControl("1"); + iuiRoute.setStatus("1"); + iuiRoute.setServers(servers); + + Assert.assertEquals(iuiRoute, IuiRouteServiceWrapper.getInstance() + .getIuiRouteInstance("microservices", "msb", "", "ip")); + + CustomRouteInfo customRoute = new CustomRouteInfo(); + customRoute.setServiceName("/custom"); + customRoute.setUrl("/custom"); + customRoute.setHost("msb"); + customRoute.setControl("1"); + customRoute.setStatus("1"); + RouteServer[] servers2 = new RouteServer[1]; + servers2[0] = new RouteServer("127.0.0.1", "8066"); + customRoute.setServers(servers2); + + Assert.assertEquals(customRoute, + CustomRouteServiceWrapper.getInstance() + .getCustomRouteInstance("/custom", "msb", "", "ip")); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_initMetricsConfig() { + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + SimpleServerFactory simpleServerFactory = new SimpleServerFactory(); + HttpConnectorFactory httpConnectorFactory = new HttpConnectorFactory(); + httpConnectorFactory.setPort(8888); + simpleServerFactory.setConnector(httpConnectorFactory); + simpleServerFactory.setAdminContextPath("/admin"); + + configuration.setServerFactory(simpleServerFactory); + + initRouteServiceWrapper.initMetricsConfig(configuration); + + Assert.assertEquals("http://127.0.0.1:8888/admin/metrics", ConfigUtil + .getInstance().getMetricsUrl()); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java new file mode 100644 index 0000000..7451e9b --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java @@ -0,0 +1,212 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.IuiRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; +import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class IuiRouteServiceWrapperTest { + private static IuiRouteServiceWrapper iuiRouteServiceWrapper; + private static Comparator<IuiRouteInfo> iuiRouteComparator = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + iuiRouteServiceWrapper=IuiRouteServiceWrapper.getInstance(); + iuiRouteComparator = new Comparator<IuiRouteInfo>() { + @Override + public int compare(IuiRouteInfo o1, IuiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + + @Test + public void test_getIuiRouteInstance_not_exist(){ + try { + iuiRouteServiceWrapper.getIuiRouteInstance("testForJunit","","","ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + + } + + @Test + public void test_getIuiRouteInstance(){ + + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + IuiRouteInfo dbIuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals(iuirouteInfo,dbIuiRouteInfo ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_getAllIuiRouteInstances(){ + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); + List<IuiRouteInfo> expected = new ArrayList<>(); + expected.add(iuirouteInfo); + expected.add(iuirouteInfo2); + Collections.sort(expected, iuiRouteComparator); + + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); + + + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); + List<IuiRouteInfo> iuiRouterList=iuiRouteServiceWrapper.getAllIuiRouteInstances("ip"); + Collections.sort(iuiRouterList, iuiRouteComparator); + + Assert.assertEquals(expected,iuiRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_updateIuiRouteStatus(){ + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + IuiRouteInfo dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals("1",dbIuirouteInfo.getStatus() ); + iuiRouteServiceWrapper.updateIuiRouteStatus("testiui","","","0", "ip"); + dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals("0",dbIuirouteInfo.getStatus() ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + + @Test + public void test_deleteIuiRoute(){ + IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); + IuiRouteInfo dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui2","","","ip"); + Assert.assertNotNull(dbIuirouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + iuiRouteServiceWrapper.deleteIuiRoute("testiui2","","","ip"); + iuiRouteServiceWrapper.getIuiRouteInstance("testiui2","","","ip"); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } + + + private IuiRouteInfo buildIuiRouteInfo(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + iuirouteInfo.setServers(servers); + return iuirouteInfo; + } + + private IuiRouteInfo buildIuiRouteInfo2(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui2"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("1"); + iuirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; + iuirouteInfo.setServers(servers); + return iuirouteInfo; + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java new file mode 100644 index 0000000..d830397 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java @@ -0,0 +1,294 @@ +package org.onap.msb.apiroute.wrapper; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.MicroServiceFullInfo; +import org.onap.msb.apiroute.api.Node; +import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; +import org.onap.msb.apiroute.api.exception.UnprocessableEntityException; +import org.onap.msb.apiroute.wrapper.MicroServiceWrapper; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class MicroServiceWrapperTest { + private static MicroServiceWrapper microServiceWrapper; + private static Comparator<MicroServiceFullInfo> microServiceComparator = null; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + microServiceWrapper=MicroServiceWrapper.getInstance(); + microServiceComparator = new Comparator<MicroServiceFullInfo>() { + @Override + public int compare(MicroServiceFullInfo o1, MicroServiceFullInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_getMicroServiceFullInfo_not_exist(){ + try { + microServiceWrapper.getMicroServiceInstance("testForJunit","v1"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + + } + + @Test + public void test_getMicroServiceFullInfo(){ + + MicroServiceFullInfo microServiceFullInfo = buildMicroServiceFullInfo(); + try { + microServiceWrapper.saveMicroServiceInstance(microServiceFullInfo, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals(microServiceFullInfo,dbMicroServiceFullInfo ); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + + } + + @Test + public void test_getAllMicroServiceInstances(){ + MicroServiceFullInfo microService = buildMicroServiceFullInfo(); + MicroServiceFullInfo microService2 = buildMicroServiceFullInfo2(); + List<MicroServiceFullInfo> expected = new ArrayList<>(); + expected.add(microService); + expected.add(microService2); + Collections.sort(expected, microServiceComparator); + + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + microServiceWrapper.saveMicroServiceInstance(microService2, false, "", ""); + + List<MicroServiceFullInfo> microServiceList=microServiceWrapper.getAllMicroServiceInstances(); + Collections.sort(microServiceList, microServiceComparator); + + Assert.assertEquals(expected,microServiceList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + @Test + public void test_updateMicroServiceStatus(){ + MicroServiceFullInfo microService = buildMicroServiceFullInfo(); + + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals("1",dbMicroServiceFullInfo.getStatus() ); + microServiceWrapper.updateMicroServiceStatus("testService","v1","0"); + dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals("0",dbMicroServiceFullInfo.getStatus() ); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + + @Test + public void test_deleteMicroService(){ + MicroServiceFullInfo microService = buildMicroServiceFullInfo2(); + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + Assert.assertNotNull(dbMicroServiceFullInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + microServiceWrapper.deleteMicroService("testService2","v1"); + microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } + + @Test + public void test_deleteMicroServiceInstance(){ + + + //娣诲姞澶氱増鏈湇鍔 + MicroServiceFullInfo microService4v2 = buildMicroServiceFullInfo4version2(); + try { + microServiceWrapper.saveMicroServiceInstance(microService4v2, false, "", ""); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + //鍒犻櫎涓嶅瓨鍦ㄥ疄渚 + try { + microServiceWrapper.deleteMicroServiceInstance("testService","v2","127.0.0.1","8989"); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + //鍒犻櫎鍏朵腑涓涓疄渚 + microServiceWrapper.deleteMicroServiceInstance("testService","v2","10.74.148.87","8080"); + MicroServiceFullInfo microService =microServiceWrapper.getMicroServiceInstance("testService", "v2"); + + Set<Node> nodeSet=new HashSet<Node>(); + nodeSet.add(new Node("10.74.148.86","8080")); + Assert.assertEquals(nodeSet, microService.getNodes()); + + //鍒犻櫎鏈嶅姟 + microServiceWrapper.deleteMicroServiceInstance("testService","v2","10.74.148.86","8080"); + } + catch(Exception e){ + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + microServiceWrapper.getMicroServiceInstance("testService","v2"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + } + + @Test + public void test_getAllVersion(){ + try { + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo4version2(), false, "", ""); + Set<String> versionSet=new HashSet<String>(); + versionSet.add("v1"); + versionSet.add("v2"); + Assert.assertEquals(versionSet,microServiceWrapper.getAllVersion("testService")); + + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + microServiceWrapper.deleteMicroService4AllVersion("testService"); + Assert.assertEquals(0,microServiceWrapper.getAllVersion("testService").size()); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + + } + + @Test + public void test_getAllMicroServiceKey(){ + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo2(), false, "", ""); + Set<String> builder = new HashSet<String>(); + builder.add("testService"); + builder.add("testService2"); + Assert.assertEquals(builder,microServiceWrapper.getAllMicroServiceKey()); + + + } + + private MicroServiceFullInfo buildMicroServiceFullInfo(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("HTTP"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4version2(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v2"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("HTTP"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.87","8080")); + nodeSet.add(new Node("10.74.148.86","8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo2(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService2"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/api/testService/v1"); + microServiceFullInfo.setVisualRange("1"); + microServiceFullInfo.setProtocol("REST"); + microServiceFullInfo.setEnable_ssl(true); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.89","8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java new file mode 100644 index 0000000..abf5e09 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java @@ -0,0 +1,149 @@ +package org.onap.msb.apiroute.wrapper.consulextend; + +import java.util.List; + +import org.apache.http.HttpEntity; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.msb.apiroute.wrapper.consulextend.CatalogClient; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.HealthClient; +import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; +import org.onap.msb.apiroute.wrapper.consulextend.async.OriginalConsulResponse; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.option.CatalogOptions; +import com.orbitz.consul.option.QueryOptions; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Http.class }) +@PowerMockIgnore({ "javax.net.ssl.*" }) +public class ConsulTest { + private static Consul consul10081; + private static Consul consul8500; + + private static final Logger LOGGER = LoggerFactory + .getLogger(ConsulTest.class); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + Http http = PowerMockito.mock(Http.class); + + PowerMockito + .doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) + throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(null); + return null; + } + }) + .when(http) + .asyncGet(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + // + consul10081 = Consul.builder().withHostAndPort("10.74.148.111", 10081) + .build(); + consul8500 = Consul.builder().withHostAndPort("10.74.148.111", 8500) + .build(); + } + + @Test + public void testcatalogClient() { + + ConsulResponseCallback<HttpEntity> callback = new ConsulResponseCallback<HttpEntity>() { + + @Override + public void onComplete( + ConsulResponse<HttpEntity> consulResponse) { + LOGGER.info("service list complete!"); + } + + @Override + public void onFailure(Throwable throwable) { + LOGGER.info("service list failure!"); + } + + @Override + public void onDelayComplete( + OriginalConsulResponse<HttpEntity> originalConsulResponse) { + // TODO Auto-generated method stub + LOGGER.info("service list complete!"); + } + + }; + + // 10081 + CatalogClient catalogclient10081 = consul10081.catalogClient(); + catalogclient10081.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); + + // 8500 + CatalogClient catalogclient8500 = consul8500.catalogClient(); + catalogclient8500.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); + } + + @Test + public void testhealthClient() { + + ConsulResponseCallback<List<ServiceHealth>> callback = new ConsulResponseCallback<List<ServiceHealth>>() { + + @Override + public void onComplete( + ConsulResponse<List<ServiceHealth>> consulResponse) { + LOGGER.info("health service complete!"); + + } + + @Override + public void onFailure(Throwable throwable) { + LOGGER.info("health service failure!"); + } + + @Override + public void onDelayComplete( + OriginalConsulResponse<List<ServiceHealth>> originalConsulResponse) { + // TODO Auto-generated method stub + LOGGER.info("health service complete!"); + } + + }; + + // 10081 + HealthClient healthClient10081 = consul10081.healthClient(); + healthClient10081.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, + QueryOptions.BLANK, callback); + + healthClient10081.getHealthyServiceInstances("apigateway-default", + CatalogOptions.BLANK, QueryOptions.BLANK, callback); + + // 8500 + HealthClient healthClient8500 = consul8500.healthClient(); + healthClient8500.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, + QueryOptions.BLANK, callback); + healthClient8500.getHealthyServiceInstances("apigateway-default", CatalogOptions.BLANK, + QueryOptions.BLANK, callback); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java new file mode 100644 index 0000000..03cc209 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java @@ -0,0 +1,24 @@ +package org.onap.msb.apiroute.wrapper.consulextend.cache; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.cache.ServiceHealthCache; + +import com.orbitz.consul.option.CatalogOptions; + +public class ServiceHealthCacheTest { + + @Test + public void testnewCache() { + Consul consul = Consul.newClient(); + ServiceHealthCache cache1 = ServiceHealthCache.newCache( + consul.healthClient(), "huangleibo"); + Assert.assertNotNull(cache1); + + ServiceHealthCache cache2 = ServiceHealthCache.newCache( + consul.healthClient(), "huangleibo", false, + CatalogOptions.BLANK, 10); + Assert.assertNotNull(cache2); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java new file mode 100644 index 0000000..7518ad7 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java @@ -0,0 +1,15 @@ +package org.onap.msb.apiroute.wrapper.consulextend.cache; + +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.cache.ServicesCatalogCache; + +public class ServicesCatalogCacheTest { + + @Test + public void testnewCache() + { + Consul consul = Consul.newClient(); + ServicesCatalogCache cache = ServicesCatalogCache.newCache(consul.catalogClient()); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java new file mode 100644 index 0000000..9b9dd17 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java @@ -0,0 +1,53 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + + + + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.expose.CheckServiceDataEmptyAndAutoStopWatchFilter; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; + +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.model.health.ImmutableNode; + +public class CheckServiceDataEmptyAndAutoStopWatchFilterTest { + @Test + public void testfilter() + { + + + CheckServiceDataEmptyAndAutoStopWatchFilter filter = new CheckServiceDataEmptyAndAutoStopWatchFilter("huangleibo"); + + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + //id:huangleibo1,name:huangleibo,modifyIndex:1,createindex:1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() + .service(service0) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + + list.add(serviceHealth0); + ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>(list,1,true, BigInteger.valueOf(1)); + + //have service,return true + Assert.assertTrue(filter.filter(object)); + + //empty [],return false + list.clear(); + Assert.assertFalse(filter.filter(object)); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java new file mode 100644 index 0000000..bd9fe3a --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java @@ -0,0 +1,70 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.expose.CheckTagAndAutoStopWatchFilter; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; + +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.model.health.ImmutableNode; + +public class CheckTagAndAutoStopWatchFilterTest { + + @Test + public void testfilter() { + + CheckTagAndAutoStopWatchFilter filter = new CheckTagAndAutoStopWatchFilter("huangleibo"); + + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + //visual range:0,tags meet conditions + List<String> tags = new ArrayList<String>(); + tags.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tags.add("\"ns\":{\"namespace\":\"nsName\"}"); + tags.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + + Service service0 = ImmutableService.builder().id("huangleibo1").port(0) + .address("").service("huangleibo").tags(tags).createIndex(1) + .modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() + .service(service0) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + + list.add(serviceHealth0); + ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>(list,1,true,BigInteger.valueOf(1)); + + //visual range:0,tags meet conditions,return true + Assert.assertTrue(filter.filter(object)); + + //visual range:1,tags don't meet conditions + List<String> tags1 = new ArrayList<String>(); + tags1.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tags1.add("\"ns\":{\"namespace\":\"nsName\"}"); + tags1.add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + + Service service1 = ImmutableService.builder().id("huangleibo1").port(0) + .address("").service("huangleibo").tags(tags1).createIndex(1) + .modifyIndex(1).build(); + ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder() + .service(service1) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + list.clear(); + list.add(serviceHealth1); + + //visual range:1,tags don't meet conditions,return false + Assert.assertFalse(filter.filter(object)); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java new file mode 100644 index 0000000..51dfa49 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java @@ -0,0 +1,42 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.expose.ConsulIndexFilter; + +import com.orbitz.consul.model.ConsulResponse; + +public class ConsulIndexFilterTest { + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + } + + @Test + public void testfilter() + { + ConsulIndexFilter<Integer> filter = new ConsulIndexFilter<Integer>(); + + int response = 1; + long lastContact= 1; + boolean knownLeader = true; + + ConsulResponse<Integer> object = new ConsulResponse<Integer>(response,lastContact,knownLeader,BigInteger.valueOf(1)); + + //index 1;the first time,return true + Assert.assertTrue(filter.filter(object)); + + + //index 1;same index,return false + Assert.assertFalse(filter.filter(object)); + + ConsulResponse<Integer> object1 = new ConsulResponse<Integer>(response,lastContact,knownLeader,BigInteger.valueOf(2)); + + //index 2;different index,return true + Assert.assertTrue(filter.filter(object1)); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java new file mode 100644 index 0000000..bc01589 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java @@ -0,0 +1,114 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.expose.ServiceModifyIndexFilter; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; + +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.model.health.ImmutableNode; + +public class ServiceModifyIndexFilterTest { + + @Test + public void testfilter() + { + ServiceModifyIndexFilter filter = new ServiceModifyIndexFilter(); + + + List<ServiceHealth> list0 = new ArrayList<ServiceHealth>(); + + //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() + .service(service0) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + list0.add(serviceHealth0); + + ConsulResponse<List<ServiceHealth>> object0 = new ConsulResponse<List<ServiceHealth>>(list0,1,true,BigInteger.valueOf(1)); + + //list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;the first time:return true + Assert.assertTrue(filter.filter(object0)); + + //list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;same index:return false + Assert.assertFalse(filter.filter(object0)); + + ///////////////////////////////////////////////////////////////////////////////// + + List<ServiceHealth> list1 = new ArrayList<ServiceHealth>(); + + //id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 + Service service1 = ImmutableService.builder().id("huangleibo2").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder() + .service(service1) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + + list1.add(serviceHealth0); + list1.add(serviceHealth1); + + ConsulResponse<List<ServiceHealth>> object1 = new ConsulResponse<List<ServiceHealth>>(list1,1,true,BigInteger.valueOf(1)); + + //list-size:2, + //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + //id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 + //size different,return true + Assert.assertTrue(filter.filter(object1)); + + ////////////////////////////////////////////////////////////////////////// + List<ServiceHealth> list2 = new ArrayList<ServiceHealth>(); + + //id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 + ImmutableService service2 = ImmutableService.builder().id("huangleibo3").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth2 = ImmutableServiceHealth.builder() + .service(service2) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + list2.add(serviceHealth0); + list2.add(serviceHealth2); + + ConsulResponse<List<ServiceHealth>> object2 = new ConsulResponse<List<ServiceHealth>>(list2,1,true,BigInteger.valueOf(1)); + + //list-size:2, + //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + //id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 + //instance id different,return true + Assert.assertTrue(filter.filter(object2)); + + + ////////////////////////////////////////////////////////////////////////// + List<ServiceHealth> list3 = new ArrayList<ServiceHealth>(); + + //edit modifyindex 1 to 2 + Service service3 = service2.withModifyIndex(2); + ServiceHealth serviceHealth3 = ImmutableServiceHealth.builder() + .service(service3) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + list3.add(serviceHealth0); + list3.add(serviceHealth3); + + ConsulResponse<List<ServiceHealth>> object3 = new ConsulResponse<List<ServiceHealth>>(list3,1,true,BigInteger.valueOf(1)); + + //list-size:2, + //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + //id:huangleibo3,name:huangleibo,modifyIndex:2,createIndex:1 + //modifyIndex different,return true + Assert.assertTrue(filter.filter(object3)); + + //the same content,return false + Assert.assertFalse(filter.filter(object3)); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java new file mode 100644 index 0000000..14455ee --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java @@ -0,0 +1,138 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchCatalogServicesTask; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask.Filter; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.option.CatalogOptions; +import com.orbitz.consul.option.QueryOptions; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Http.class }) +@PowerMockIgnore({ "javax.net.ssl.*" }) +public class WatchCatalogServicesTaskTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(WatchCatalogServicesTaskTest.class); + + private Consul consul; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Before + public void init() { + + Map<String, List<String>> catalogservices = new HashMap<String, List<String>>(); + String servicename = "huangleibo"; + List<String> tags = new ArrayList<String>(); + tags.add("1111"); + tags.add("2222"); + catalogservices.put(servicename, tags); + + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + final ConsulResponse<Map<String, List<String>>> response = new ConsulResponse<Map<String, List<String>>>( + catalogservices, lastContact, knownLeader, index); + + // + Http http = PowerMockito.mock(Http.class); + + PowerMockito + .doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) + throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(response); + return null; + } + }) + .when(http) + .asyncGet(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + consul = Consul.newClient(); + + WatchCatalogServicesTask task0 = new WatchCatalogServicesTask( + consul.catalogClient(), CatalogOptions.BLANK, + QueryOptions.BLANK, 10); + + WatchCatalogServicesTask task1 = new WatchCatalogServicesTask( + consul.catalogClient(), 10); + + WatchCatalogServicesTask task2 = new WatchCatalogServicesTask( + consul.catalogClient()); + + } + + public class StopHandler implements WatchTask.Handler<HttpEntity> + { + + private WatchCatalogServicesTask task; + + StopHandler(WatchCatalogServicesTask task) + { + this.task = task; + } + + @Override + public void handle(ConsulResponse<HttpEntity> object) { + // TODO Auto-generated method stub +// Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); + LOGGER.debug("handler is here"); + task.stopWatch(); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void teststartWatch() { + WatchCatalogServicesTask task0 = new WatchCatalogServicesTask( + consul.catalogClient(), CatalogOptions.BLANK, + QueryOptions.BLANK, 10); + + task0.addFilter(new Filter() { + @Override + public boolean filter(ConsulResponse object) { + // TODO Auto-generated method stub +// Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); + LOGGER.debug("filter is here"); + return true; + } + + }); + + task0.addHandler(new StopHandler(task0)); + + task0.startWatch(); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java new file mode 100644 index 0000000..0e5f95b --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java @@ -0,0 +1,156 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.msb.apiroute.wrapper.consulextend.Consul; +import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchServiceHealthTask; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask.Filter; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.model.health.ImmutableNode; +import com.orbitz.consul.option.CatalogOptions; +import com.orbitz.consul.option.QueryOptions; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Http.class }) +@PowerMockIgnore({ "javax.net.ssl.*" }) +public class WatchServiceHealthTaskTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(WatchServiceHealthTaskTest.class); + + private Consul consul; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Before + public void init() { + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + Service service = ImmutableService.builder().id("").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder() + .service(service) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + list.add(serviceHealth); + + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + final ConsulResponse<List<ServiceHealth>> response = new ConsulResponse<List<ServiceHealth>>( + list, lastContact, knownLeader, index); + + // + Http http = PowerMockito.mock(Http.class); + + PowerMockito + .doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) + throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(response); + return null; + } + }) + .when(http) + .asyncGet(Mockito.anyString(), + Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + } + + @Test + public void testgetServiceName() { + consul = Consul.newClient(); + + WatchServiceHealthTask task0 = new WatchServiceHealthTask( + consul.healthClient(), "huangleibo_task0", true, + CatalogOptions.BLANK, 10, QueryOptions.BLANK); + + LOGGER.info("service name:" + task0.getServiceName()); + + WatchServiceHealthTask task1 = new WatchServiceHealthTask( + consul.healthClient(), "huangleibo_task1", true, 10); + + LOGGER.debug("service name:" + task1.getServiceName()); + + WatchServiceHealthTask task2 = new WatchServiceHealthTask( + consul.healthClient(), "huangleibo_task2", 10); + + LOGGER.debug("service name:" + task2.getServiceName()); + + } + + public class StopHandler implements WatchTask.Handler<List<ServiceHealth>> + { + + private WatchServiceHealthTask task; + + StopHandler(WatchServiceHealthTask task) + { + this.task = task; + } + + @Override + public void handle(ConsulResponse<List<ServiceHealth>> object) { + // TODO Auto-generated method stub + List<ServiceHealth> list = (List<ServiceHealth>)object.getResponse(); + LOGGER.debug("handler:"+list.get(0).getService().getService()); + task.stopWatch(); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void teststartWatch() { + Consul consul = Consul.newClient(); + String serviceName = "huangleibo"; + + WatchServiceHealthTask task0 = new WatchServiceHealthTask( + consul.healthClient(), serviceName, true, CatalogOptions.BLANK, + 10, QueryOptions.BLANK); + + task0.addFilter(new Filter() { + + @Override + public boolean filter(ConsulResponse object) { + // TODO Auto-generated method stub + List<ServiceHealth> list = (List<ServiceHealth>)object.getResponse(); + LOGGER.debug("filter:"+list.get(0).getService().getService()); + return true; + } + + }); + + task0.addHandler(new StopHandler(task0)); + + task0.startWatch(); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java new file mode 100644 index 0000000..a86baf1 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java @@ -0,0 +1,46 @@ +package org.onap.msb.apiroute.wrapper.consulextend.expose; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.expose.WriteBufferHandler; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.queue.ServiceData; + +import com.orbitz.consul.model.ConsulResponse; +import com.orbitz.consul.model.health.ImmutableNode; + +public class WriteBufferHandlerTest { + @Test + public void testhandle() { + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + // modifyIndex 1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0) + .address("").service("huangleibo").addTags("").createIndex(1) + .modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() + .service(service0) + .node(ImmutableNode.builder().node("").address("").build()) + .build(); + + list.add(serviceHealth0); + + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>( + list, lastContact, knownLeader, index); + + WriteBufferHandler<List<ServiceHealth>> handler = new WriteBufferHandler<List<ServiceHealth>>( + ServiceData.DataType.service); + + handler.handle(object); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java new file mode 100644 index 0000000..008a28d --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java @@ -0,0 +1,54 @@ +package org.onap.msb.apiroute.wrapper.consulextend.model.health; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; + +import com.orbitz.consul.model.health.HealthCheck; +import com.orbitz.consul.model.health.ImmutableHealthCheck; +import com.orbitz.consul.model.health.ImmutableNode; +import com.orbitz.consul.model.health.Node; + +public class ServiceHealthTest { + + @Test + public void TestImmutableServiceHealth() { + Service service = ImmutableService.builder().id("").port(0).address("") + .service("huangleibo").addTags("").createIndex(1) + .modifyIndex(1).build(); + Node node = ImmutableNode.builder().node("").address("").build(); + + HealthCheck healthCheck0 = ImmutableHealthCheck.builder().checkId("") + .name("").node("").notes("").output("").serviceId("") + .serviceName("").status("").build(); + HealthCheck healthCheck1 = ImmutableHealthCheck.builder().checkId("") + .name("").node("").notes("").output("").serviceId("") + .serviceName("").status("").build(); + HealthCheck healthCheck2 = ImmutableHealthCheck.builder().checkId("") + .name("").node("").notes("").output("").serviceId("") + .serviceName("").status("").build(); + + ImmutableServiceHealth serviceHealth0 = ImmutableServiceHealth + .builder().service(service).node(node).addChecks(healthCheck0) + .addChecks(healthCheck1, healthCheck2).build(); + + Assert.assertNotNull(serviceHealth0.getNode()); + Assert.assertNotNull(serviceHealth0.getChecks()); + /* ############################################################### */ + + ImmutableServiceHealth serviceHealth1 = serviceHealth0.withNode(node) + .withNode(ImmutableNode.builder().node("").address("").build()) + .withService(service).withService(ImmutableService.builder().id("").port(0).address("") + .service("huangleibo1111").addTags("").createIndex(1) + .modifyIndex(1).build()).withChecks(healthCheck0); + + Assert.assertFalse(serviceHealth1.equals(serviceHealth0)); + System.out.println(serviceHealth1.hashCode()); + + /* ############################################################### */ + + ImmutableServiceHealth serviceHealth2 = ImmutableServiceHealth.builder().from(serviceHealth1).build(); + Assert.assertTrue(serviceHealth1.equals(serviceHealth2)); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java new file mode 100644 index 0000000..81629c5 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java @@ -0,0 +1,32 @@ +package org.onap.msb.apiroute.wrapper.consulextend.model.health; + +import org.junit.Assert; +import org.junit.Test; + +public class ServiceTest { + + @Test + public void testImmutableService() { + ImmutableService service0 = ImmutableService.builder() + .id("huangleibo_id").port(0).address("").service("huangleibo") + .addTags("111", "222").createIndex(1).modifyIndex(1).build(); + Assert.assertEquals("huangleibo_id", service0.getId()); + Assert.assertEquals(1, service0.getCreateIndex()); + Assert.assertEquals(1, service0.getModifyIndex()); + + ImmutableService service1 = service0.withId("huangleibo_id") + .withId("new_id").withService("huangleibo") + .withService("new_service").withTags("new_tags") + .withAddress("").withAddress("new_address").withPort(0) + .withPort(1).withCreateIndex(1).withCreateIndex(2) + .withModifyIndex(1).withModifyIndex(2); + + Assert.assertFalse(service0.equals(service1)); + + System.out.println(service1.hashCode()); + + ImmutableService service2 = ImmutableService.builder().from(service1) + .build(); + Assert.assertEquals("new_id", service2.getId()); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java new file mode 100644 index 0000000..af2197e --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java @@ -0,0 +1,80 @@ +package org.onap.msb.apiroute.wrapper.consulextend.util; + +import java.io.InputStream; +import java.math.BigInteger; +import java.util.List; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicStatusLine; +import org.junit.Before; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.consulextend.util.Http; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.orbitz.consul.option.ConsistencyMode; +import com.orbitz.consul.option.ImmutableCatalogOptions; +import com.orbitz.consul.option.ImmutableQueryOptions; +import com.orbitz.consul.option.QueryOptions; + +public class HttpTest { + private static final Logger LOGGER = LoggerFactory + .getLogger(HttpTest.class); + + @Before + public void init() { + + } + + @Test + public void testoptionsFrom() { + ImmutableCatalogOptions catalogs = ImmutableCatalogOptions.builder() + .build(); + catalogs = catalogs.withDatacenter("datacenter").withTag("tag"); + + BigInteger index = new BigInteger("1"); + ImmutableQueryOptions querys = QueryOptions.blockSeconds(10, index) + .build(); + querys = querys.withConsistencyMode(ConsistencyMode.STALE) + .withDatacenter("datacenter").withNear("near") + .withToken("taoken"); + String url = Http.optionsFrom(catalogs, querys); + LOGGER.info(url); + } + + @Test + public void testconsulResponse() { + + TypeReference<Map<String, List<String>>> TYPE_SERVICES_MAP = new TypeReference<Map<String, List<String>>>() {}; + + ProtocolVersion version = new ProtocolVersion("HTTP",1,1); + StatusLine status= new BasicStatusLine(version,200,"ok"); + BasicHttpResponse response = new BasicHttpResponse(status); + + response.setHeader("X-Consul-Index", "1"); + response.setHeader("X-Consul-Lastcontact", "1"); + response.setHeader("X-Consul-Knownleader", "true"); + + BasicHttpEntity entity = new BasicHttpEntity(); + InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content); + response.setEntity(entity); + + Http.consulResponse(TYPE_SERVICES_MAP, response); + + TypeReference<String> TYPE_SERVICES_MAP_STRING = new TypeReference<String>() {}; + InputStream content1 = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content1); + + Http.consulResponse(TYPE_SERVICES_MAP_STRING, response); + + TypeReference<HttpEntity> TYPE_SERVICES_MAP_ENTITY = new TypeReference<HttpEntity>() {}; + Http.consulResponse(TYPE_SERVICES_MAP_ENTITY, response); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java new file mode 100644 index 0000000..a76575f --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java @@ -0,0 +1,178 @@ +package org.onap.msb.apiroute.wrapper.queue; + +import java.io.InputStream; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.BasicHttpEntity; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.SyncDataManager; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.util.HttpTest; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.queue.QueueManager; +import org.onap.msb.apiroute.wrapper.queue.ServiceConsumer; +import org.onap.msb.apiroute.wrapper.queue.ServiceData; +import org.onap.msb.apiroute.wrapper.queue.ServiceListConsumer; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; +import com.orbitz.consul.model.health.ImmutableNode; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class QueueManagerTest { + private static QueueManager queueManager; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + queueManager=QueueManager.getInstance(); + putInServiceListQueue(); + putInServiceQueue4Update(); + + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + + + public void test_ServiceConsumer(){ + + //start ServiceListConsumer +// new Thread(new ServiceListConsumer(this),"ServiceListConsumerThread").start(); + + //start Service Consumer + int serviceQueneNum=RouteUtil.SERVICE_DATA_QUEUE_NUM; + for(int i=0;i<serviceQueneNum;i++){ + new Thread(new ServiceConsumer(i),"ServiceConsumerThread"+i).start(); + } + + } + + + public void test_ServiceListConsumer(){ + + //start ServiceListConsumer + new Thread(new ServiceListConsumer(),"ServiceListConsumerThread").start(); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + putInServiceQueue4Delete(); + } + + + + private static void putInServiceListQueue(){ + ServiceData<HttpEntity> data=new ServiceData<HttpEntity>(); + data.setDataType(ServiceData.DataType.service_list); + + BasicHttpEntity entity = new BasicHttpEntity(); + InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content); + data.setData(entity); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } + } + + private static void putInServiceQueue4Update(){ + ServiceData<List<ServiceHealth>> data=new ServiceData<List<ServiceHealth>>(); + data.setDataType(ServiceData.DataType.service); + data.setOperate(ServiceData.Operate.delete); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = + ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = + ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + data.setData(serviceHealthList); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } + } + + private static void putInServiceQueue4Delete(){ + ServiceData<List<ServiceHealth>> data=new ServiceData<List<ServiceHealth>>(); + data.setDataType(ServiceData.DataType.service); + data.setOperate(ServiceData.Operate.update); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = + ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = + ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + data.setData(serviceHealthList); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java new file mode 100644 index 0000000..a5aa87a --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java @@ -0,0 +1,251 @@ +package org.onap.msb.apiroute.wrapper.service; + +import com.fiftyonred.mock_jedis.MockJedisPool; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.ApiRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.service.ApiRouteService; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class ApiRouteServiceTest { + private static ApiRouteService apiRouteService = null; + private static Comparator<ApiRouteInfo> apiRouteComparator = null; + @BeforeClass + public static void setUp() throws Exception{ + apiRouteService = ApiRouteService.getInstance(); + apiRouteComparator = new Comparator<ApiRouteInfo>() { + @Override + public int compare(ApiRouteInfo o1, ApiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + if (!o1.getVersion().equals(o2.getVersion())) + return (o1.getVersion()).compareTo(o2.getVersion()); + return 0; + } + }; + } + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + @Test + public void testGetApiRouteInstance_key_not_exist(){ + try { + assertNull(apiRouteService.getApiRouteInstance("msb:routing:api:notexistservice:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetApiRouteInstance_key_exist(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + apirouteInfo.setServers(servers); + try { + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testSaveApiRouteService2Redis(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + apirouteInfo.setServers(servers); + try { + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testSaveApiRouteService2Redis2(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("test26msb"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/microservices/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.151.26","443")}; + apirouteInfo.setServers(servers); + try { + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:test26msb:v1"); + assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:test26msb:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testDeleteApiRouteService2Redis(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + apirouteInfo.setServers(servers); + try { + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + assertNotNull(apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); + apiRouteService.deleteApiRouteService2Redis("msb:routing:api:testapi:v1"); + assertNull(apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testUpdateApiRouteStatus2Redis(){ + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + apirouteInfo.setServers(servers); + try { + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + assertEquals("1", apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1").getStatus()); + apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:testapi:v1","0"); + assertEquals("0", apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1").getStatus()); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetMultiApiRouteInstances() throws Exception { + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); + apirouteInfo2.setServiceName("testapi"); + apirouteInfo2.setVersion("v2"); + apirouteInfo2.setStatus("0"); + apirouteInfo2.setUrl("/api/testapi/v2"); + apirouteInfo2.setUseOwnUpstream("0"); + apirouteInfo2.setVisualRange("0");; + apirouteInfo.setEnable_ssl(true); + apirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo2,"msb:routing:api:testapi:v2"); + + List<ApiRouteInfo> expected = new ArrayList<>(); + expected.add(apirouteInfo); + expected.add(apirouteInfo2); + Collections.sort(expected, apiRouteComparator); + + List<ApiRouteInfo> result = apiRouteService.getMultiApiRouteInstances("msb:routing:api:*"); + + Collections.sort(result, apiRouteComparator); + assertEquals(expected, result); + } + + @Test + public void testDeleteMultiApiRouteInstances() throws Exception { + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); + apirouteInfo2.setServiceName("testapi"); + apirouteInfo2.setVersion("v2"); + apirouteInfo2.setStatus("0"); + apirouteInfo2.setUrl("/api/testapi/v2"); + apirouteInfo2.setUseOwnUpstream("0"); + apirouteInfo2.setVisualRange("0");; + apirouteInfo.setEnable_ssl(true); + apirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo2,"msb:routing:api:testapi:v2"); + + assertEquals(2,apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); + assertEquals(2,apiRouteService.deleteMultiApiRouteService2Redis("msb:routing:api:testapi:*")); + assertEquals(0,apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); + } + + @Test(expected = Exception.class) + public void testUpdateApiRouteStatus2Redis_keyNotExist() throws Exception { + apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:notexistservice:v1","0"); + } + + @Test(expected = Exception.class) + public void testSaveApiRouteService2Redis_null() throws Exception { + apiRouteService.saveApiRouteService2Redis(null,"msb:routing:api:null:v1"); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java new file mode 100644 index 0000000..d34958b --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java @@ -0,0 +1,241 @@ +package org.onap.msb.apiroute.wrapper.service; + +import com.fiftyonred.mock_jedis.MockJedisPool; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.CustomRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.service.CustomRouteService; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class CustomRouteServiceTest { + private static CustomRouteService customRouteService = null; + private static Comparator<CustomRouteInfo> customRouteComparator = null; + @BeforeClass + public static void setUp() throws Exception{ + customRouteService = CustomRouteService.getInstance(); + customRouteComparator = new Comparator<CustomRouteInfo>() { + @Override + public int compare(CustomRouteInfo o1, CustomRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + } + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + @Test + public void testGetCustomRouteInstance_key_not_exist(){ + try { + assertNull(customRouteService.getCustomRouteInstance("msb:routing:custom:notexistservice:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetCustomRouteInstance_key_exist(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + try { + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testSaveCustomRouteService2Redis(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom/v1"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + try { + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testSaveCustomRouteService2Redis_urlIsSlash(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + try { + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + customrouteInfo.setUrl(""); + assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testDeleteCustomRouteService2Redis(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom/v1"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + try { + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + assertNotNull(customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); + customRouteService.deleteCustomRouteService2Redis("msb:routing:custom:testcustom"); + assertNull(customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testUpdateCustomRouteStatus2Redis(){ + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom/v1"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + customrouteInfo.setServers(servers); + try { + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + assertEquals("1", customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom").getStatus()); + customRouteService.updateCustomRouteStatus2Redis("msb:routing:custom:testcustom", "0"); + assertEquals("0", customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom").getStatus()); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetMultiCustomRouteInstances() throws Exception { + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); + customrouteInfo2.setServiceName("testcustom2"); + customrouteInfo2.setStatus("0"); + customrouteInfo2.setUrl("/custom/testcustom2"); + customrouteInfo2.setUseOwnUpstream("0"); + customrouteInfo2.setVisualRange("0");; + customrouteInfo.setEnable_ssl(true); + customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + customRouteService.saveCustomRouteService2Redis(customrouteInfo2, "msb:routing:custom:testcustom2"); + + List<CustomRouteInfo> expected = new ArrayList<>(); + expected.add(customrouteInfo); + expected.add(customrouteInfo2); + Collections.sort(expected, customRouteComparator); + + List<CustomRouteInfo> result = customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*"); + + Collections.sort(result, customRouteComparator); + assertEquals(expected, result); + } + + @Test + public void testDeleteMultiCustomRouteInstances() throws Exception { + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); + customrouteInfo2.setServiceName("testcustom2"); + customrouteInfo2.setStatus("0"); + customrouteInfo2.setUrl("/custom/testcustom2"); + customrouteInfo2.setUseOwnUpstream("0"); + customrouteInfo2.setVisualRange("0");; + customrouteInfo.setEnable_ssl(true); + customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); + customRouteService.saveCustomRouteService2Redis(customrouteInfo2, "msb:routing:custom:testcustom2"); + + assertEquals(2,customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); + assertEquals(2,customRouteService.deleteMultiCustomRouteService2Redis("msb:routing:custom:*")); + assertEquals(0, customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); + } + + @Test(expected = Exception.class) + public void testUpdateCustomRouteStatus2Redis_keyNotExist() throws Exception { + customRouteService.updateCustomRouteStatus2Redis("msb:routing:custom:notexistservice", "0"); + } + + @Test(expected = Exception.class) + public void testSaveCustomRouteService2Redis_null() throws Exception { + customRouteService.saveCustomRouteService2Redis(null, "msb:routing:custom:null"); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java new file mode 100644 index 0000000..0ddbb32 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java @@ -0,0 +1,221 @@ +package org.onap.msb.apiroute.wrapper.service; + +import com.fiftyonred.mock_jedis.MockJedisPool; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.IuiRouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.service.IuiRouteService; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class IuiRouteServiceTest { + private static IuiRouteService iuiRouteService = null; + private static Comparator<IuiRouteInfo> iuiRouteComparator = null; + @BeforeClass + public static void setUp() throws Exception{ + iuiRouteService = IuiRouteService.getInstance(); + iuiRouteComparator = new Comparator<IuiRouteInfo>() { + @Override + public int compare(IuiRouteInfo o1, IuiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + } + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + @Test + public void testGetIuiRouteInstance_key_not_exist(){ + try { + assertNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:notexistservice:v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetIuiRouteInstance_key_exist(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + iuirouteInfo.setServers(servers); + try { + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + assertEquals(iuirouteInfo, iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testSaveIuiRouteService2Redis(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui/v1"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + iuirouteInfo.setServers(servers); + try { + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + assertEquals(iuirouteInfo, iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testDeleteIuiRouteService2Redis(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui/v1"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + iuirouteInfo.setServers(servers); + try { + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + assertNotNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); + iuiRouteService.deleteIuiRouteService2Redis("msb:routing:iui:testiui"); + assertNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testUpdateIuiRouteStatus2Redis(){ + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui/v1"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + iuirouteInfo.setServers(servers); + try { + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + assertEquals("1", iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui").getStatus()); + iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:testiui","0"); + assertEquals("0", iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui").getStatus()); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetMultiIuiRouteInstances() throws Exception { + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); + iuirouteInfo2.setServiceName("testiui2"); + iuirouteInfo2.setStatus("0"); + iuirouteInfo2.setUrl("/iui/testiui2"); + iuirouteInfo2.setUseOwnUpstream("0"); + iuirouteInfo2.setVisualRange("0");; + iuirouteInfo.setEnable_ssl(true); + iuirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2,"msb:routing:iui:testiui2"); + + List<IuiRouteInfo> expected = new ArrayList<>(); + expected.add(iuirouteInfo); + expected.add(iuirouteInfo2); + Collections.sort(expected, iuiRouteComparator); + + List<IuiRouteInfo> result = iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*"); + + Collections.sort(result, iuiRouteComparator); + assertEquals(expected, result); + } + + @Test + public void testDeleteMultiIuiRouteInstances() throws Exception { + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); + iuirouteInfo2.setServiceName("testiui2"); + iuirouteInfo2.setStatus("0"); + iuirouteInfo2.setUrl("/iui/testiui2"); + iuirouteInfo2.setUseOwnUpstream("0"); + iuirouteInfo2.setVisualRange("0");; + iuirouteInfo.setEnable_ssl(true); + iuirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2,"msb:routing:iui:testiui2"); + + assertEquals(2,iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); + assertEquals(2,iuiRouteService.deleteMultiIuiRouteService2Redis("msb:routing:iui:*")); + assertEquals(0,iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); + } + + @Test(expected = Exception.class) + public void testUpdateIuiRouteStatus2Redis_keyNotExist() throws Exception { + iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:notexistservice","0"); + } + + @Test(expected = Exception.class) + public void testSaveIuiRouteService2Redis_null() throws Exception { + iuiRouteService.saveIuiRouteService2Redis(null,"msb:routing:iui:null"); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java new file mode 100644 index 0000000..7ca2ff7 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java @@ -0,0 +1,413 @@ +package org.onap.msb.apiroute.wrapper.service; + +import com.fiftyonred.mock_jedis.MockJedisPool; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.MicroServiceFullInfo; +import org.onap.msb.apiroute.api.Node; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.service.MicroServiceFullService; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.MicroServiceUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.*; + +import static org.junit.Assert.*; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) +@PowerMockIgnore( {"javax.management.*"}) +public class MicroServiceFullServiceTest { + private static MicroServiceFullService microServiceFullService = null; + private static Comparator<MicroServiceFullInfo> serviceComparator = null; + @BeforeClass + public static void setUp() throws Exception{ + microServiceFullService = MicroServiceFullService.getInstance(); + serviceComparator = new Comparator<MicroServiceFullInfo>() { + @Override + public int compare(MicroServiceFullInfo o1, MicroServiceFullInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + if (!o1.getVersion().equals(o2.getVersion())) + return (o1.getVersion()).compareTo(o2.getVersion()); + return 0; + } + }; + } + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void testExistsMicroServiceInstance_notExist(){ + try { + assertFalse(microServiceFullService.existsMicroServiceInstance("notExist", "v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + @Test + public void testExistsMicroServiceInstance_Exist(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + try { + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "v1")); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + assertTrue(microServiceFullService.existsMicroServiceInstance("testService", "v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + + @Test + public void testSaveMicroServiceInfo2Redis(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + MicroServiceFullInfo actual = microServiceFullService.getMicroServiceInstance("testService", "v1"); + assertEquals(microServiceFullInfo, actual); + } catch (Exception e) { + e.printStackTrace(); + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testDeleteMicroService(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + assertTrue(microServiceFullService.existsMicroServiceInstance("testService", "v1")); + microServiceFullService.deleteMicroService("testService","v1"); + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + + @Test + public void testUpdateMicroServiceStatus(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","v1").getStatus()); + microServiceFullService.updateMicroServiceStatus("testService", "v1", "0"); + assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", "v1").getStatus()); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void testGetAllMicroServiceKey(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + + MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); + microServiceFullInfo2.setServiceName("testService2"); + microServiceFullInfo2.setVersion(""); + microServiceFullInfo2.setStatus("1"); + microServiceFullInfo2.setUrl("/testService2"); + microServiceFullInfo2.setVisualRange("0"); + microServiceFullInfo2.setProtocol("http"); + microServiceFullInfo2.setEnable_ssl(false); + Set<Node> nodeSet2 = new HashSet<>(); + nodeSet2.add(new Node("10.74.148.88","8081")); + microServiceFullInfo2.setNodes(nodeSet2); + + MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); + microServiceFullInfo3.setServiceName("testService"); + microServiceFullInfo3.setVersion("v2"); + microServiceFullInfo3.setStatus("1"); + microServiceFullInfo3.setUrl("/testService/v2"); + microServiceFullInfo3.setVisualRange("0"); + microServiceFullInfo3.setProtocol("http"); + microServiceFullInfo3.setEnable_ssl(false); + Set<Node> nodeSet3 = new HashSet<>(); + nodeSet3.add(new Node("10.74.148.89","8080")); + microServiceFullInfo3.setNodes(nodeSet3); + + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo2); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); + + Set<String> result = microServiceFullService.getAllMicroServiceKey(); + final Set<String> expected =new HashSet<String>(); + expected.add("testService"); + expected.add("testService2"); + + assertEquals(expected, result); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + + } + + @Test + public void testGetAllVersionsOfTheService(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + + MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); + microServiceFullInfo2.setServiceName("testService2"); + microServiceFullInfo2.setVersion(""); + microServiceFullInfo2.setStatus("1"); + microServiceFullInfo2.setUrl("/testService2"); + microServiceFullInfo2.setVisualRange("0"); + microServiceFullInfo2.setProtocol("http"); + microServiceFullInfo2.setEnable_ssl(false); + Set<Node> nodeSet2 = new HashSet<>(); + nodeSet2.add(new Node("10.74.148.88","8081")); + microServiceFullInfo2.setNodes(nodeSet2); + + MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); + microServiceFullInfo3.setServiceName("testService"); + microServiceFullInfo3.setVersion("v2"); + microServiceFullInfo3.setStatus("1"); + microServiceFullInfo3.setUrl("/testService/v2"); + microServiceFullInfo3.setVisualRange("0"); + microServiceFullInfo3.setProtocol("http"); + microServiceFullInfo3.setEnable_ssl(false); + Set<Node> nodeSet3 = new HashSet<>(); + nodeSet3.add(new Node("10.74.148.89","8080")); + microServiceFullInfo3.setNodes(nodeSet3); + + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo2); + + + List<MicroServiceFullInfo> result = microServiceFullService.getAllVersionsOfTheService("testService"); + + List<MicroServiceFullInfo> expected = new ArrayList<>(); + expected.add(microServiceFullInfo); + expected.add(microServiceFullInfo3); + + Collections.sort(expected,serviceComparator); + Collections.sort(result,serviceComparator); + assertEquals(expected, result); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + + } + + @Test + public void testGetAllMicroServicesInstances(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + + MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); + microServiceFullInfo2.setServiceName("testService2"); + microServiceFullInfo2.setVersion(""); + microServiceFullInfo2.setStatus("1"); + microServiceFullInfo2.setUrl("/testService/v1"); + microServiceFullInfo2.setVisualRange("0"); + microServiceFullInfo2.setProtocol("http"); + microServiceFullInfo2.setEnable_ssl(true); + Set<Node> nodeSet2 = new HashSet<>(); + nodeSet2.add(new Node("10.74.148.89","8080")); + microServiceFullInfo2.setNodes(nodeSet2); + + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo2); + + List<MicroServiceFullInfo> expected = new ArrayList<MicroServiceFullInfo>(); + expected.add(microServiceFullInfo); + expected.add(microServiceFullInfo2); + List<MicroServiceFullInfo> result = microServiceFullService.getAllMicroServiceInstances(); + Collections.sort(expected, serviceComparator); + Collections.sort(result,serviceComparator ); + assertEquals(expected, result); + } catch (Exception e) { + e.printStackTrace(); + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + + @Test + public void testDeleteMultiMicroService(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + + + MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); + microServiceFullInfo3.setServiceName("testService"); + microServiceFullInfo3.setVersion("v2"); + microServiceFullInfo3.setStatus("1"); + microServiceFullInfo3.setUrl("/testService/v2"); + microServiceFullInfo3.setVisualRange("0"); + microServiceFullInfo3.setProtocol("http"); + microServiceFullInfo3.setEnable_ssl(false); + Set<Node> nodeSet3 = new HashSet<>(); + nodeSet3.add(new Node("10.74.148.89","8080")); + microServiceFullInfo3.setNodes(nodeSet3); + + try { + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); + //two versions of testservice exist + assertEquals(2,microServiceFullService.getAllVersionsOfTheService("testService").size()); + //delete all versions of testservice + long size = microServiceFullService.deleteMultiMicroService(MicroServiceUtil.getPrefixedKey("testService","*")); + //after delete,no version exist + assertEquals(0,microServiceFullService.getAllVersionsOfTheService("testService").size()); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test + public void tesGetMicroServiceInstance_notExist(){ + try { + assertNull(microServiceFullService.getMicroServiceInstance("notExist","v1")); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + + } + @Test + public void tesExistsGetUpdateDeleteMicroServiceStatus_versionNull(){ + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion(""); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("http"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88","8080")); + microServiceFullInfo.setNodes(nodeSet); + try { + //test null + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","null").getStatus()); + microServiceFullService.updateMicroServiceStatus("testService", "null", "0"); + assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", "null").getStatus()); + microServiceFullService.deleteMicroService("testService","null"); + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); + + + //test String "null" + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); + microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService",null).getStatus()); + microServiceFullService.updateMicroServiceStatus("testService", null, "0"); + assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", null).getStatus()); + microServiceFullService.deleteMicroService("testService",null); + assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); + } catch (Exception e) { + assert false:"throw exception means error occured!"+e.getMessage(); + } + } + + @Test(expected = Exception.class) + public void tesSaveMicroService_null() throws Exception { + microServiceFullService.saveMicroServiceInfo2Redis(null); + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java new file mode 100644 index 0000000..f537e0e --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java @@ -0,0 +1,666 @@ +package org.onap.msb.apiroute.wrapper.serviceListener; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.ApiRouteAppConfig; +import org.onap.msb.apiroute.api.ApiRouteInfo; +import org.onap.msb.apiroute.api.CustomRouteInfo; +import org.onap.msb.apiroute.api.DiscoverInfo; +import org.onap.msb.apiroute.api.IuiRouteInfo; +import org.onap.msb.apiroute.api.MicroServiceFullInfo; +import org.onap.msb.apiroute.api.Node; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; +import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; +import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; +import org.onap.msb.apiroute.wrapper.serviceListener.RouteNotify; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; +import org.onap.msb.apiroute.wrapper.util.RouteUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +import com.fiftyonred.mock_jedis.MockJedisPool; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JedisUtil.class,ConfigUtil.class,HttpClientUtil.class, RedisAccessWrapper.class,}) +@PowerMockIgnore({"javax.management.*"}) +public class MicroServiceChangeListenerTest { + private static RouteNotify routeInstance; + private static ApiRouteServiceWrapper apiRouteServiceWrapper; + private static IuiRouteServiceWrapper iuiRouteServiceWrapper; + private static CustomRouteServiceWrapper customRouteServiceWrapper; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + InitRouteServiceWrapper.getInstance().registerServiceChangeListener(); + routeInstance=RouteNotify.getInstance(); + apiRouteServiceWrapper=ApiRouteServiceWrapper.getInstance(); + iuiRouteServiceWrapper=IuiRouteServiceWrapper.getInstance(); + customRouteServiceWrapper=CustomRouteServiceWrapper.getInstance(); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); + } + + @Before + public void initReidsMock() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_noticeRouteListener4Update_api(){ + try { + routeInstance.noticeRouteListener4Update("apiTest-ns", "v1", buildMicroServiceFullInfo4API()); + ApiRouteInfo apiRouteInfo=apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); + + Assert.assertNotNull(apiRouteInfo); + Assert.assertEquals("1", apiRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4API(),"0"); + apiRouteInfo=apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); + Assert.assertEquals("0", apiRouteInfo.getStatus()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Update_iui(){ + try { + routeInstance.noticeRouteListener4Update("iuiTest-ns", "v1", buildMicroServiceFullInfo4IUI()); + IuiRouteInfo iuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); + + Assert.assertNotNull(iuiRouteInfo); + Assert.assertEquals("1", iuiRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4IUI(),"0"); + iuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); + Assert.assertEquals("0", iuiRouteInfo.getStatus()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Update_http(){ + try { + routeInstance.noticeRouteListener4Update("httpTest-ns", "v1", buildMicroServiceFullInfo4HTTP()); + CustomRouteInfo customRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); + Assert.assertNotNull(customRouteInfo); + Assert.assertEquals("1", customRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4HTTP(),"0"); + customRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); + Assert.assertEquals("0", customRouteInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Add_del_api(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest-ns", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest-ns", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + + } + + @Test + public void test_noticeRouteListener4Add_del_api_path(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip")); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip")); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_api_mutiPort(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip")); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_iui(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest-ns", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "iuitest-ns", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_iui_path(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + + @Test + public void test_noticeRouteListener4Add_del_iui_mutiPort(){ + try { + MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_http(){ + try { + MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest-ns", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest-ns", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_http_path(){ + try { + MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + + @Test + public void test_noticeRouteListener4Add_del_http_mutiPort(){ + try { + MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest", "", "domain"); + Assert.fail("should not process to here."); + } + catch(Exception e){ + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + + @Test + public void test_noticeRouteListener4Add_portal(){ + try { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); + ApiRouteAppConfig configuration=new ApiRouteAppConfig(); + + DiscoverInfo discoverInfo=new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.2"); + discoverInfo.setPort(10081); + configuration.setDiscoverInfo(discoverInfo); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + + + PowerMockito.mockStatic(HttpClientUtil.class); + String publishUrl="http://127.0.0.1:10081/api/microservices/v1/services/portalTest/version/v1/allpublishaddress?namespace=&visualRange=0"; + String resultJson ="[{\"domain\":\"opapi.openpalette.zte.com.cn\",\"port\":\"443\",\"publish_url\":\"/api\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"443\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"80\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"http\"}]"; + PowerMockito.when(HttpClientUtil.httpGet(publishUrl)).thenReturn(resultJson); + + MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4PORTAL(); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + + CustomRouteInfo routeInfo_ip=customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "", "10088", "ip"); + RouteServer[] servers_ip = new RouteServer[]{new RouteServer("10.74.148.99","8080")}; + Assert.assertArrayEquals(servers_ip, routeInfo_ip.getServers()); + + CustomRouteInfo routeInfo_domain=customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "host", "", "domain"); + RouteServer[] servers_domain = new RouteServer[]{new RouteServer("10.74.165.246","443")}; + + Assert.assertArrayEquals(servers_domain, routeInfo_domain.getServers()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } + + + private MicroServiceFullInfo buildMicroServiceFullInfo4API(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("apiTest-ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("REST"); + microServiceInfo.setUrl("/api/apiTest/v1"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + microServiceInfo.setNamespace("ns"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4API_path(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("apiTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPath("/api/apiTest4Path/v1"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setProtocol("REST"); + microServiceInfo.setUrl("/api/apiTest/v1"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + + private MicroServiceFullInfo buildMicroServiceFullInfo4PORTAL(){ + + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("portalTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPublish_port("10088"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/portalTestUrl/v1"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setStatus("1"); + microServiceInfo.setCustom(RouteUtil.CUSTOM_PORTAL); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.99","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4IUI(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("iuiTest-ns"); + microServiceInfo.setNamespace("ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("UI"); + microServiceInfo.setUrl("/iui/iuiTest"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4IUI_path(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("iuiTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setProtocol("UI"); + microServiceInfo.setUrl("/iui/iuiTest"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setPath("/iui/iuiTest4Path"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("httpTest-ns"); + microServiceInfo.setNamespace("ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/httpTest"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP_path(){ + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("httpTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/httpTest"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setStatus("1"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setPath("/httpTest4Path"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88","8080")); + nodes.add(new Node("10.74.148.89","8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java new file mode 100644 index 0000000..825868c --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java @@ -0,0 +1,61 @@ +package org.onap.msb.apiroute.wrapper.util; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.util.CommonUtil; + +public class CommonUtilTest { + + + + @Test + public void test_concat() { + Object[] str1 = new String[] {"test1", "test2"}; + Object[] str2 = new String[] {"test3"}; + Object[] str3 = CommonUtil.concat(str1, str2); + + Assert.assertEquals(3, str3.length); + } + + @Test + public void test_containStr() { + String value = "1"; + String array[] = {"1", "2"}; + Assert.assertTrue(CommonUtil.contain(array, value)); + Assert.assertFalse(CommonUtil.contain(array, "3")); + } + + @Test + public void test_containArray() { + String value[] = {"0"}; + String array[] = {"1", "2"}; + String array2[] = {"2", "1"}; + Assert.assertFalse(CommonUtil.contain(array, value)); + Assert.assertTrue(CommonUtil.contain(array, array2)); + } + + @Test + public void test_containStrArray() { + Assert.assertFalse(CommonUtil.contain("0,1,2", "3")); + Assert.assertTrue(CommonUtil.contain("0,1,2", "1")); + } + + @Test + public void test_getDiffrent() { + Set<String> list1 = new HashSet<String>(); + list1.add("test1"); + list1.add("test2"); + + Set<String> list2 = new HashSet<String>(); + list2.add("test2"); + list2.add("test3"); + + Set<String> diff = CommonUtil.getDiffrent(list1, list2); + Assert.assertEquals(1, diff.size()); + Assert.assertTrue(diff.contains("test3")); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java new file mode 100644 index 0000000..e17c177 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java @@ -0,0 +1,214 @@ +package org.onap.msb.apiroute.wrapper.util; + + + +import java.lang.reflect.Field; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.ApiRouteAppConfig; +import org.onap.msb.apiroute.api.DiscoverInfo; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ConfigUtil.class}) +public class ConfigUtilTest { + + @Test + public void test_initRootPath() { + try { + ConfigUtil.getInstance().initRootPath(); + String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); + String apiRootPath = ConfigUtil.getInstance().getAPI_ROOT_PATH(); + Assert.assertEquals("iui", iuiRootPath); + Assert.assertEquals("api", apiRootPath); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + + } + + } + + @Test + public void test_initApiGatewayPort() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); + ConfigUtil.getInstance().initApiGatewayPort(); + Assert.assertEquals("80", ConfigUtil.getInstance().getServerPort()); + + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn("81"); + + ConfigUtil.getInstance().initApiGatewayPort(); + Assert.assertEquals("81", ConfigUtil.getInstance().getServerPort()); + } + + @Test + public void test_initRouteNameSpaceMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertEquals("all", ConfigUtil.getInstance().getNamespaceMatches()); + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("net"); + + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertEquals("net", ConfigUtil.getInstance().getNamespaceMatches()); + } + + @Test + public void test_initRouteLabelsMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn(null); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("0", ConfigUtil.getInstance().getVisualRangeMatches()); + Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); + Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom-key")); + + + + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("visualRange:1,network_plane_type:net,custom:test"); + + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("1", ConfigUtil.getInstance().getVisualRangeMatches()); + Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); + Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom")); + + } + + @Test + public void test_initRouteWay() { + PowerMockito.mockStatic(System.class); + + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + ConfigUtil.getInstance().initRouteWay(); + String[] ip_routeWay={"ip"}; + Assert.assertArrayEquals(ip_routeWay, ConfigUtil.getInstance().getRouteWay()); + + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + + ConfigUtil.getInstance().initRouteWay(); + String[] routeWay={"ip","domain"}; + Assert.assertArrayEquals(routeWay, ConfigUtil.getInstance().getRouteWay()); + } + + @Test + public void test_initDiscoverInfo() { + PowerMockito.mockStatic(System.class); + + + ApiRouteAppConfig configuration=new ApiRouteAppConfig(); + + DiscoverInfo discoverInfo=new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.1"); + discoverInfo.setPort(10081); + + configuration.setDiscoverInfo(discoverInfo); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn(null); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + Assert.assertEquals("127.0.0.1:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); + + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("10.74.44.86"); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + Assert.assertEquals("10.74.44.86:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); + } + + @Test + public void test_initNodeMeta() { + + //CONSUL_REGISTER_MODE not catalog + ConfigUtil util=ConfigUtil.getInstance(); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),""); + + //CONSUL_REGISTER_MODE catalog + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("agnet"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),""); + + + //CONSUL_REGISTER_MODE catalog + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("catalog"); + try { + Field visualRangeField=util.getClass().getDeclaredField("visualRangeMatches"); + visualRangeField.setAccessible(true); + + Field namespaceField = util.getClass().getDeclaredField("namespaceMatches"); + namespaceField.setAccessible(true); + + //0:default; + visualRangeField.set(util, "0"); + namespaceField.set(util, "default"); + + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=external:true&node-meta=ns:default"); + + //1:default; + visualRangeField.set(util, "1"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true&node-meta=ns:default"); + + //0|1:default + visualRangeField.set(util, "0|1"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=ns:default"); + + //0|1:all + namespaceField.set(util, "all"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),""); + + /////////////////////////////////////////////////////////////////////////// + //1:all + visualRangeField.set(util, "1"); + namespaceField.set(util, "all"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); + + //1:! + namespaceField.set(util, "!default"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); + + //1:& + namespaceField.set(util, "tenant1&tenant2"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); + + //1:| + namespaceField.set(util, "tenant1|tenant2"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); + + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java new file mode 100644 index 0000000..568e4f9 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java @@ -0,0 +1,29 @@ +package org.onap.msb.apiroute.wrapper.util; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; + +public class HttpClientUtilTest { + + private String testIp="http://10.74.151.26:8500"; + + @Test + public void test_httpGet() { + /*try { + int result = HttpClientUtil.httpGetStatus(testIp); + if(result==200){ + Assert.assertEquals("Consul Agent", HttpClientUtil.httpGet(testIp)); + } + else{ + Assert.assertEquals(500, result); + } + + + } catch (Exception e) { + Assert.assertTrue(e instanceof IOException); + }*/ + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java new file mode 100644 index 0000000..f9835d9 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java @@ -0,0 +1,94 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper.util; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.api.PublishFullAddress; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; + +import com.fasterxml.jackson.core.type.TypeReference; + + +public class JacksonJsonUtilTest { + @Test + public void testBeanToJson(){ + try{ + RouteServer server=new RouteServer("127.0.0.1","80"); + String json=JacksonJsonUtil.beanToJson(server); + Assert.assertEquals("{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}",json); + } + catch(Exception e){ + Assert.fail("Exception" + e.getMessage()); + } + } + + @Test + public void testJsonToBean(){ + try{ + String json="{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}"; + RouteServer server=(RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); + Assert.assertEquals("127.0.0.1",server.getIp()); + Assert.assertEquals("80",server.getPort()); + } + catch(Exception e){ + Assert.fail("Exception" + e.getMessage()); + } + } + + +// @Test +// public void testJsonToBean_Fail(){ +// try{ +// String json="{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0"; +// RouteServer server=(RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); +// } +// catch(Exception e){ +// Assert.assertEquals("class org.onap.msb.apiroute.api.RouteServer JsonTobean faild",e.getMessage()); +// } +// } + + @Test + public void testJsonToListBean(){ + try{ + String resultJson="[{\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," + + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; + List<PublishFullAddress> publishFullAddressList = + JacksonJsonUtil.jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); + Assert.assertEquals(2,publishFullAddressList.size()); + Assert.assertEquals("80",publishFullAddressList.get(0).getPort()); + } + catch(Exception e){ + Assert.fail("Exception" + e.getMessage()); + } + } + + @Test + public void testJsonToListBean_Fail(){ + try{ + String resultJson="[\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," + + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; + List<PublishFullAddress> publishFullAddressList = + JacksonJsonUtil.jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); + } + catch(Exception e){ + Assert.assertTrue(e instanceof Exception); + } + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java new file mode 100644 index 0000000..5a92e32 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java @@ -0,0 +1,20 @@ +package org.onap.msb.apiroute.wrapper.util; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.util.JedisUtil; + +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class JedisUtilTest { + @Test + public void test_initialPool() { + try { + JedisUtil.borrowJedisInstance(); + + } catch (Exception e) { + Assert.assertTrue(e instanceof JedisConnectionException); + + } + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java new file mode 100644 index 0000000..2012413 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java @@ -0,0 +1,45 @@ +package org.onap.msb.apiroute.wrapper.util; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.wrapper.util.MicroServiceUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import redis.clients.jedis.Jedis; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({HttpServletRequest.class}) +public class MicroServiceUtilTest { + + @Test + public void test_getPrefixedKey(){ + Assert.assertEquals("discover:microservices:test:v1",MicroServiceUtil.getPrefixedKey("test","v1")); + } + + @Test + public void test_getServiceKey(){ + Assert.assertEquals("discover:microservices:test:v1",MicroServiceUtil.getServiceKey("test","v1")); + } + + @Test + public void test_getRealIp(){ + HttpServletRequest request=PowerMockito.mock(HttpServletRequest.class); + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn("127.0.0.1"); + Assert.assertEquals("127.0.0.1",MicroServiceUtil.getRealIp(request)); + + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); + PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn("127.0.0.2"); + Assert.assertEquals("127.0.0.2",MicroServiceUtil.getRealIp(request)); + + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); + PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn(""); + PowerMockito.when(request.getRemoteAddr()).thenReturn("127.0.0.3"); + Assert.assertEquals("127.0.0.3",MicroServiceUtil.getRealIp(request)); + + } +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java new file mode 100644 index 0000000..11e5907 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java @@ -0,0 +1,96 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper.util; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.msb.apiroute.wrapper.util.RegExpTestUtil; + +public class RegExpTestUtilTest { + + @Test + public void test_HostRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.hostRegExpTest("127.0.0.1:8080")); + Assert.assertFalse(RegExpTestUtil.hostRegExpTest("0.0.0.1:89")); + } + + + + @Test + public void test_IpRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.ipRegExpTest("127.0.0.1")); + Assert.assertFalse(RegExpTestUtil.ipRegExpTest("127.0.0.1.5")); + } + + + + @Test + public void test_PortRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.portRegExpTest("80")); + Assert.assertFalse(RegExpTestUtil.portRegExpTest("898989")); + } + + + @Test + public void test_VersionRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.versionRegExpTest("v1")); + Assert.assertFalse(RegExpTestUtil.versionRegExpTest("23")); + } + + + + @Test + public void test_urlRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/test")); + Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/")); + Assert.assertFalse(RegExpTestUtil.urlRegExpTest("test")); + } + + + @Test + public void test_apiRouteUrlRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.apiRouteUrlRegExpTest("/api/test/v1")); + Assert.assertFalse(RegExpTestUtil.apiRouteUrlRegExpTest("/test")); + } + + + + @Test + public void test_iuiRouteUrlRegExpTest(){ + Assert.assertTrue(RegExpTestUtil.iuiRouteUrlRegExpTest("/iui/test")); + Assert.assertFalse(RegExpTestUtil.iuiRouteUrlRegExpTest("/test")); + } + + @Test + public void test_apiServiceNameMatch4URL(){ + String[] apiServiceNameArray={"testApiName","v1"}; + Assert.assertArrayEquals(apiServiceNameArray, RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName/v1")); + + String[] apiServiceNameArray_noversion={"testApiName",""}; + Assert.assertArrayEquals(apiServiceNameArray_noversion, RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName")); + + Assert.assertNull(RegExpTestUtil.apiServiceNameMatch4URL("/apiw/name/v1")); + } + + @Test + public void test_iuiServiceNameMatch4URL(){ + String iuiServiceName="testIuiName"; + Assert.assertEquals(iuiServiceName, RegExpTestUtil.iuiServiceNameMatch4URL("/iui/testIuiName")); + + Assert.assertNull(RegExpTestUtil.iuiServiceNameMatch4URL("/api/name/v1")); + } + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java new file mode 100644 index 0000000..7ddab84 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java @@ -0,0 +1,373 @@ +/** + * Copyright 2016 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.msb.apiroute.wrapper.util; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.MicroServiceFullInfo; +import org.onap.msb.apiroute.api.Node; +import org.onap.msb.apiroute.api.RouteInfo; +import org.onap.msb.apiroute.api.RouteServer; +import org.onap.msb.apiroute.api.exception.UnprocessableEntityException; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ConfigUtil.class}) +public class RouteUtilTest { + + @Test + public void test_getPrefixedKey() { + Assert.assertEquals("msb:routing:test:v1", RouteUtil.getPrefixedKey("", "test", "v1")); + Assert.assertEquals("msb:5656:test:v1", RouteUtil.getPrefixedKey("5656", "test", "v1")); + + } + + @Test + public void test_getPrefixedKey4Host() { + Assert.assertEquals("msb:host:test:v1", RouteUtil.getPrefixedKey4Host("test", "v1")); + + } + + + + @Test + public void test_checkRouteWay() { + try { + RouteUtil.checkRouteWay("ipp"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + + } + + @Test + public void test_checkServiceNameAndVersion() { + try { + RouteUtil.checkServiceNameAndVersion("","v1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + + try { + RouteUtil.checkServiceNameAndVersion("test","ve1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkServiceStatus() { + try { + RouteUtil.checkServiceStatus("2"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkRouterInfoFormat() { + RouteInfo routeInfo=new RouteInfo(); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_ip() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88.22","8080")); + microServiceInfo.setNodes(nodeSet); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_port() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88.22","808770")); + microServiceInfo.setNodes(nodeSet); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_version() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("","8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("cv2"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_url() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("","8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("v2"); + microServiceInfo.setUrl("url"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_protocol() { + MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST2"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("","8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("v2"); + microServiceInfo.setUrl("/url"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_getAPIRedisPrefixedKey() { + Assert.assertEquals("msb:20081:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","20081","ip")); + Assert.assertEquals("msb:routing:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","","ip")); + Assert.assertEquals("msb:host:testHost:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","20081","domain")); + } + + @Test + public void test_getRedisPrefixedKey() { + Assert.assertEquals("msb:20081:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","20081","ip")); + Assert.assertEquals("msb:routing:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","","ip")); + Assert.assertEquals("msb:host:testHost:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","20081","domain")); + + Assert.assertEquals("msb:20081:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","20081","ip")); + Assert.assertEquals("msb:routing:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","","ip")); + Assert.assertEquals("msb:host:testHost:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","20081","domain")); + } + + @Test + public void test_getMutiRedisKey() { + Assert.assertEquals("msb:[^h]*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE,"ip")); + Assert.assertEquals("msb:[^h]*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE,"ip")); + Assert.assertEquals("msb:[^h]*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE,"ip")); + + Assert.assertEquals("msb:host:*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE,"domain")); + Assert.assertEquals("msb:host:*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE,"domain")); + Assert.assertEquals("msb:host:*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE,"domain")); + } + + @Test + public void test_getRouteNameByns() { + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName","")); + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName-ns","ns")); + Assert.assertEquals("serviceName-ns", RouteUtil.getRouteNameByns("serviceName-ns-ns","ns")); + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName","default")); + } + + @Test + public void test_getVisualRangeByRouter(){ + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); + Assert.assertEquals("1", RouteUtil.getVisualRangeByRouter("1")); + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0")); + + + } + + @Test + public void test_getVisualRangeByRouter_muti(){ + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:0|1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); + } + + @Test + public void test_checkRouterInfoFormat_url() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkRouterInfoFormat_visualRangeRange() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + routeInfo.setVisualRange("2"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + + @Test + public void test_checkRouterInfoFormat_controlRangeMatches() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkRouterInfoFormat_statusRangeMatches() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + + @Test + public void test_checkRouterInfoFormat_useOwnUpstreamRangeMatches() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkRouterInfoFormat_ip() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88.6","8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("1"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + + @Test + public void test_checkRouterInfoFormat_port() { + RouteInfo routeInfo=new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88.6","757577")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("1"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + + + + + + + +} diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java new file mode 100644 index 0000000..e7c6531 --- /dev/null +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java @@ -0,0 +1,210 @@ +package org.onap.msb.apiroute.wrapper.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.msb.apiroute.api.MicroServiceFullInfo; +import org.onap.msb.apiroute.api.Node; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableService; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ImmutableServiceHealth; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.Service; +import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; +import org.onap.msb.apiroute.wrapper.util.ConfigUtil; +import org.onap.msb.apiroute.wrapper.util.ServiceFilter; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.orbitz.consul.model.health.ImmutableNode; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ConfigUtil.class}) +public class ServiceFilterTest { + + + + @Test + public void test_isNeedNotifyByNameSpace() { + + PowerMockito.mockStatic(System.class); + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("all"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test")); // namespaceMatches:all + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("default"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:default + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:default + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("default"));// namespaceMatches:default + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!default"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:!default + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:!default + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns|ns2"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("")); + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!ns&!ns2"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); + + } + + /* + * @Test public void test_isNeedNotifyByVisualRange(){ + * + * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0")); + * Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByVisualRange("1")); + * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0|1")); } + */ + + @Test + public void test_isNeedNotifyByProtocol() { + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("HTTP")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("UI")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("REST")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByProtocol("TCP")); + } + + @Test + public void test_isNeedNotifyByNetwork_plane_typeMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:network"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); + Assert.assertTrue(ServiceFilter.getInstance() + .isNeedNotifyByNetwork_plane_typeMatches("network")); + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:net1|net2"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net1")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net2")); + + } + + @Test + public void test_isNeedNotifyByRouteLabels() { + Map<String, String> labelMap = new HashMap<String, String>(); + labelMap.put("lab1", "val1"); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); + + } + + @Test + public void test_isFilterService() { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns1"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn( + "visualRange:0,network_plane_type:net,customLabel:custom|custom2"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + Assert.assertTrue(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"TCP\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns2\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net2\",\"customLabel\":\"custom\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom3\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + } + + @Test + public void test_transMicroServiceInfoFromConsul() { + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList + .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = + ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = + ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + Map<String, MicroServiceFullInfo> serviceMap= ServiceFilter.getInstance().transMicroServiceInfoFromConsul(serviceHealthList); + Assert.assertTrue(serviceMap.containsKey("v1")); + + MicroServiceFullInfo microService=new MicroServiceFullInfo(); + microService.setServiceName("msbtest"); + microService.setVersion("v1"); + microService.setUrl("/api/msbtest/v1"); + microService.setProtocol("REST"); + microService.setVisualRange("0"); + microService.setNamespace("ns1"); + + Set<Node> nodes=new HashSet<Node>(); + nodes.add(new Node("10.74.165.246","8686")); + microService.setNodes(nodes); + + + + Assert.assertEquals(microService,serviceMap.get("v1")); + + + } + + + +} diff --git a/apiroute/apiroute-service/src/test/resources/ext/initApiGatewayConfig/initApiGatewayConfig.json b/apiroute/apiroute-service/src/test/resources/ext/initApiGatewayConfig/initApiGatewayConfig.json new file mode 100644 index 0000000..67580e1 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initApiGatewayConfig/initApiGatewayConfig.json @@ -0,0 +1,3 @@ +{
+ "port" : "80"
+}
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json new file mode 100644 index 0000000..80826f2 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json @@ -0,0 +1,12 @@ +{
+ "namespace":"all",
+ "predefineLabels":
+ {
+ "visualRange" : "0",
+ "network_plane_type":"net"
+ },
+ "customLabels":
+ {
+ "custom-key":"custom-value"
+ }
+}
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json.sample b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json.sample new file mode 100644 index 0000000..1ffdbc1 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/initRouteLabelsMatches.json.sample @@ -0,0 +1,12 @@ +{
+ "namespace":"all",
+ "predefineLabels":
+ {
+ "visualRange" : "0",
+ "network_plane_type":""
+ },
+ "customLabels":
+ {
+ "customLabel":""
+ }
+}
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/readme.txt b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/readme.txt new file mode 100644 index 0000000..3e95c5c --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initRouteLabels/readme.txt @@ -0,0 +1,17 @@ +Apigateway can synchronized service informations from the service discovery by configuring filter tag。
+Synchronization filter configuration file path:apiroute\ext\initRouteLabels\initVisualRangeMatches.json,
+{
+ "namespace":"",
+ "routeLabels":
+ {
+ "visualRange" : "0",
+ "network_plane_type":""
+ }
+}
+namespace为命令空间过滤条件,值为空则忽略此项过滤,否则只有服务namespace属性与条件一致的服务才进行下一步的自定义标签匹配。
+routeLabels为自定义标签,用户可自定义键值对匹配条件,支持多项值,以|分隔。任一个标签的值满足即同步
+当同步服务信息时使用visualRange这个标签筛选,取值范围 系统间:0(默认) 系统内:1,其中系统间将对服务路由访问做鉴权处理。
+
+如果是docker部署首选在apigateway所在容器配置env环境变量获取:
+变量名:NAMESPACE
+变量名:ROUTE_LABELS 变量值格式:visualRange:0; network_plane_type:xx|yy
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/initRouteWay.json b/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/initRouteWay.json new file mode 100644 index 0000000..b6ebf27 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/initRouteWay.json @@ -0,0 +1,3 @@ +{
+ "routeWay":"ip"
+}
\ No newline at end of file diff --git a/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/readme.txt b/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/readme.txt new file mode 100644 index 0000000..c219550 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initRouteWay/readme.txt @@ -0,0 +1,5 @@ +Apigateway 路由方式:ip/domain; 默认为ip
+
+如果是docker部署首选在apigateway所在容器配置env环境变量获取:
+变量名:ROUTE_WAY 变量可选值:ip/domain
+
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initServices/msb.json b/apiroute/apiroute-service/src/test/resources/ext/initServices/msb.json new file mode 100644 index 0000000..43b795d --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initServices/msb.json @@ -0,0 +1,44 @@ +[{
+ "serviceName" : "microservices",
+ "version" : "v1",
+ "url" : "/api/microservices/v1",
+ "apiJson" : "/api/microservices/v1/swagger.json",
+ "apiJsonType" : "1",
+ "metricsUrl" : "/admin/metrics",
+ "control" : "1",
+ "status" : "1",
+ "host":"msb",
+ "servers" : [{
+ "ip" : "127.0.0.1",
+ "port" : "8066",
+ "weight" : 0
+ }
+ ]
+ },
+{
+ "serviceName" : "microservices",
+ "url" : "/iui/microservices",
+ "control" : "1",
+ "status" : "1",
+ "host":"msb",
+ "servers" : [{
+ "ip" : "127.0.0.1",
+ "port" : "8066",
+ "weight" : 0
+ }
+ ]
+ },
+ {
+ "serviceName" : "/custom",
+ "url" : "/custom",
+ "control" : "1",
+ "status" : "1",
+ "host":"msb",
+ "servers" : [{
+ "ip" : "127.0.0.1",
+ "port" : "8066",
+ "weight" : 0
+ }
+ ]
+ }
+]
diff --git a/apiroute/apiroute-service/src/test/resources/ext/initServices/readme.txt b/apiroute/apiroute-service/src/test/resources/ext/initServices/readme.txt new file mode 100644 index 0000000..59ef5e4 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initServices/readme.txt @@ -0,0 +1,63 @@ +########################## initialize default routeInfo to redis ##########################
+
+#when msb is starting, it will automatically read all json files under this folder, and initializes to redis.
+#If the routeInfo is exist, it will be ignored, otherwise it will be saved.
+
+
+# JSON File content must be routeInfo format array like below examples:
+
+# optional:
+# apiJsonType: 1:user-defined json type 0:pre-defined json type
+# control: 0:default 1:readonly 2:hidden
+# status: 0:disabled 1:enabled
+# Tip:control、status、weight are non-mandatory
+
+[
+##########################apiRoute example##########################
+
+{
+ "serviceName" : "microservices",
+ "version" : "v1",
+ "url" : "/api/microservices/v1",
+ "apiJson" : "/api/microservices/v1/swagger.json",
+ "apiJsonType" : "1",
+ "metricsUrl" : "/admin/metrics",
+ "control" : "1",
+ "status" : "1",
+ "servers" : [{
+ "ip" : "127.0.0.1",
+ "port" : "8086",
+ "weight" : 0
+ }
+ ]
+ },
+
+##########################iuiRoute example##########################
+
+{
+ "serviceName" : "microservices",
+ "url" : "/iui/microservices",
+ "control" : "1",
+ "status" : "1",
+ "servers" : [{
+ "ip" : "127.0.0.1",
+ "port" : "8086",
+ "weight" : 0
+ }
+ ]
+ },
+
+##########################customRoute example##########################
+ {
+ "serviceName" : "/test",
+ "url" : "/test",
+ "control" : "0",
+ "status" : "1",
+ "servers" : [{
+ "ip" : "10.74.56.36",
+ "port" : "8989",
+ "weight" : 0
+ }
+ ]
+ }
+]
\ No newline at end of file diff --git a/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc1.json b/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc1.json new file mode 100644 index 0000000..7c63d7e --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc1.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"version":"1.0.0","title":"Local API Test"},"basePath":"/service","tags":[{"name":"ApiRoute"}],"paths":{"/apiRoute":{"get":{"tags":["ApiRoute"],"summary":"get all ApiRoute ","description":"","operationId":"getApiRoutes","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/ApiRouteInfo"}}}}},"post":{"tags":["ApiRoute"],"summary":"add one ApiRoute ","description":"","operationId":"addApiRoute","produces":["application/json"],"parameters":[{"in":"body","name":"body","description":"ApiRoute Instance Info","required":true,"schema":{"$ref":"#/definitions/ApiRouteInfo"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteInfo"}},"500":{"description":"add ApiRoute error "}}}},"/apiRoute/type/{type}/{routeName}/version/{version}":{"get":{"tags":["ApiRoute"],"summary":"get one ApiRoute ","description":"","operationId":"getApiRoute","produces":["application/json"],"parameters":[{"name":"type","in":"path","description":"Route type","required":true,"type":"string","enum":["iui","api"]},{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteInfo"}},"500":{"description":"get ApiRoute error "}}},"delete":{"tags":["ApiRoute"],"summary":"delete one ApiRoute by routeName and version","description":"","operationId":"deleteApiRoute","produces":["application/json"],"parameters":[{"name":"type","in":"path","description":"Route type","required":true,"type":"string","enum":["iui","api"]},{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteResult"}},"500":{"description":"delete ApiRoute error "}}}},"/apiRoute/{routeName}/version/{version}":{"put":{"tags":["ApiRoute"],"summary":"update one ApiRoute by routeName and version","description":"","operationId":"updateApiRoute","produces":["application/json"],"parameters":[{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"},{"in":"body","name":"body","description":"ApiRoute Instance Info","required":true,"schema":{"$ref":"#/definitions/ApiRouteInfo"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteResult"}},"500":{"description":"update ApiRoute error "}}}}},"definitions":{"ApiRouteLifeCycle":{"type":"object","properties":{"installPath":{"type":"string"},"startScript":{"type":"string"},"stopScript":{"type":"string"}}},"ApiRouteServer":{"type":"object","properties":{"ip":{"type":"string"},"weight":{"type":"integer","format":"int32"}}},"ApiRouteResult":{"type":"object","properties":{"result":{"type":"string"},"info":{"type":"string"}}},"ApiRouteInfo":{"type":"object","properties":{"routeName":{"type":"string"},"version":{"type":"string"},"url":{"type":"string"},"apiJson":{"type":"string"},"type":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/definitions/ApiRouteServer"}},"lifeCycle":{"$ref":"#/definitions/ApiRouteLifeCycle"}}}}}
\ No newline at end of file diff --git a/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc2.json b/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc2.json new file mode 100644 index 0000000..eb7c8cd --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initSwaggerJson/api-doc2.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"version":"1.0.0","title":"Local API Test2"},"basePath":"/service","tags":[{"name":"ApiRoute"}],"paths":{"/apiRoute":{"get":{"tags":["ApiRoute"],"summary":"get all ApiRoute ","description":"","operationId":"getApiRoutes","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/ApiRouteInfo"}}}}},"post":{"tags":["ApiRoute"],"summary":"add one ApiRoute ","description":"","operationId":"addApiRoute","produces":["application/json"],"parameters":[{"in":"body","name":"body","description":"ApiRoute Instance Info","required":true,"schema":{"$ref":"#/definitions/ApiRouteInfo"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteInfo"}},"500":{"description":"add ApiRoute error "}}}},"/apiRoute/type/{type}/{routeName}/version/{version}":{"get":{"tags":["ApiRoute"],"summary":"get one ApiRoute ","description":"","operationId":"getApiRoute","produces":["application/json"],"parameters":[{"name":"type","in":"path","description":"Route type","required":true,"type":"string","enum":["iui","api"]},{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteInfo"}},"500":{"description":"get ApiRoute error "}}},"delete":{"tags":["ApiRoute"],"summary":"delete one ApiRoute by routeName and version","description":"","operationId":"deleteApiRoute","produces":["application/json"],"parameters":[{"name":"type","in":"path","description":"Route type","required":true,"type":"string","enum":["iui","api"]},{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteResult"}},"500":{"description":"delete ApiRoute error "}}}},"/apiRoute/{routeName}/version/{version}":{"put":{"tags":["ApiRoute"],"summary":"update one ApiRoute by routeName and version","description":"","operationId":"updateApiRoute","produces":["application/json"],"parameters":[{"name":"routeName","in":"path","description":"ApiRoute routeName","required":true,"type":"string"},{"name":"version","in":"path","description":"ApiRoute version","required":true,"type":"string"},{"in":"body","name":"body","description":"ApiRoute Instance Info","required":true,"schema":{"$ref":"#/definitions/ApiRouteInfo"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiRouteResult"}},"500":{"description":"update ApiRoute error "}}}}},"definitions":{"ApiRouteLifeCycle":{"type":"object","properties":{"installPath":{"type":"string"},"startScript":{"type":"string"},"stopScript":{"type":"string"}}},"ApiRouteServer":{"type":"object","properties":{"ip":{"type":"string"},"weight":{"type":"integer","format":"int32"}}},"ApiRouteResult":{"type":"object","properties":{"result":{"type":"string"},"info":{"type":"string"}}},"ApiRouteInfo":{"type":"object","properties":{"routeName":{"type":"string"},"version":{"type":"string"},"url":{"type":"string"},"apiJson":{"type":"string"},"type":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/definitions/ApiRouteServer"}},"lifeCycle":{"$ref":"#/definitions/ApiRouteLifeCycle"}}}}}
\ No newline at end of file diff --git a/apiroute/apiroute-service/src/test/resources/ext/initUrlRootPath/initUrlRootPath.json b/apiroute/apiroute-service/src/test/resources/ext/initUrlRootPath/initUrlRootPath.json new file mode 100644 index 0000000..9668592 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/initUrlRootPath/initUrlRootPath.json @@ -0,0 +1,4 @@ +{
+ "iuiRootPath" : "iui",
+ "apiRootPath" : "api"
+}
diff --git a/apiroute/apiroute-service/src/test/resources/ext/redisConf/redis.properties b/apiroute/apiroute-service/src/test/resources/ext/redisConf/redis.properties new file mode 100644 index 0000000..3703748 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/ext/redisConf/redis.properties @@ -0,0 +1,18 @@ +redis.host=127.0.0.1 +redis.port=6379 +#connectionTimeout +redis.connectionTimeout=2000 +#redis dbIndex锛宒efaule:0 +redis.db_index=0 + +#--------------redis pool config-------------- +#maxTotal +redis.pool.maxTotal=500 +#maxIdle +redis.pool.maxIdle=100 +#maxWaitMillis:ms +redis.pool.maxWaitMillis=15000 +#testOnBorrow +redis.pool.testOnBorrow=false +#testOnReturn +redis.pool.testOnReturn=true diff --git a/apiroute/apiroute-service/src/test/resources/org/onap/msb/apiroute/wrapper/consulextend/util/serviceslist.json b/apiroute/apiroute-service/src/test/resources/org/onap/msb/apiroute/wrapper/consulextend/util/serviceslist.json new file mode 100644 index 0000000..5139ca8 --- /dev/null +++ b/apiroute/apiroute-service/src/test/resources/org/onap/msb/apiroute/wrapper/consulextend/util/serviceslist.json @@ -0,0 +1 @@ +{"aaa-aaa":["\"ns\":{\"namespace\":\"aaa\"}","\"base\":{\"version\":\"v1\",\"protocol\":\"UI\",\"url\":\"/iui\",\"enable_ssl\":\"false\",\"is_manual\":\"true\",\"status\":\"1\"}","\"lb\":{\"lb_policy\":\"\"}","\"labels\":{\"visualRange\":\"1\"}"],"apigateway-default":["\"base\":{\"url\":\"/api/microservices/v1\",\"protocol\":\"REST\",\"version\":\"v1\"}","\"labels\":{\"visualRange\":\"1\"}","\"metadata\":{\"routeWay\":\"ip\"}","\"ns\":{\"namespace\":\"default\"}"],"authen":["\"lb\":{\"lb_policy\":\"\"}","\"labels\":{\"visualRange\":\"1\"}","\"base\":{\"version\":\"v1\",\"protocol\":\"HTTP\",\"url\":\"/authen/v1\",\"enable_ssl\":\"false\",\"is_manual\":\"false\",\"status\":\"1\",\"ha_role\":\"active\"}"],"author":["\"base\":{\"version\":\"v1\",\"protocol\":\"HTTP\",\"url\":\"/author/v1\",\"enable_ssl\":\"false\",\"is_manual\":\"false\",\"status\":\"1\",\"ha_role\":\"active\"}","\"lb\":{\"lb_policy\":\"\"}","\"labels\":{\"visualRange\":\"1\"}"],"bbb-bbb":["\"ns\":{\"namespace\":\"bbb\"}","\"base\":{\"version\":\"v1\",\"protocol\":\"HTTP\",\"url\":\"/iui/component\",\"enable_ssl\":\"false\",\"is_manual\":\"true\",\"status\":\"1\"}","\"lb\":{\"lb_policy\":\"\"}","\"labels\":{\"visualRange\":\"1\"}"],"br-engine":["\"base\":{\"version\":\"v1\",\"protocol\":\"HTTP\",\"url\":\"/br-engine/v1\",\"enable_ssl\":\"false\",\"is_manual\":\"false\",\"status\":\"1\",\"ha_role\":\"active\"}","\"lb\":{\"lb_policy\":\"\"}","\"labels\":{\"visualRange\":\"0|1\"}"]}
\ No newline at end of file |