diff options
author | HuabingZhao <zhao.huabing@zte.com.cn> | 2017-09-07 14:33:18 +0800 |
---|---|---|
committer | HuabingZhao <zhao.huabing@zte.com.cn> | 2017-09-07 14:40:59 +0800 |
commit | e75a8ef2372722c0b22669fb427d47bacc5b8d5e (patch) | |
tree | cee85cbc4fe818262fb8c4d733f2fac0c8024df8 /apiroute/apiroute-service/src/test/java/org | |
parent | e5fe5a022f4cc5164c1f4516c024617c49f12978 (diff) |
Fix java check style warning
Change-Id: I98a6d7237a213d007ad4d954989cb0b0fa150a10
Issue-Id: MSB-67
Signed-off-by: HuabingZhao <zhao.huabing@zte.com.cn>
Diffstat (limited to 'apiroute/apiroute-service/src/test/java/org')
38 files changed, 3746 insertions, 3999 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 index e6ab926..91ee211 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -19,7 +17,6 @@ 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; @@ -30,42 +27,33 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.fasterxml.jackson.core.type.TypeReference; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@PrepareForTest({Http.class}) +@PowerMockIgnore({"javax.net.ssl.*"}) public class SyncDataManagerTest { - @SuppressWarnings("unchecked") - @Before - public void setUpBeforeTest() { - Http http = PowerMockito.mock(Http.class); + @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).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.doNothing().when(http).asyncGetDelayHandle(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); - // - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); + // + 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(); - } + } + + @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 index 46c0632..a8223eb 100644 --- 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 @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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; @@ -29,56 +26,49 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.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"); - } - } + 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 index 309192a..2b1bc4f 100644 --- 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 @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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; @@ -29,90 +26,80 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.class,ConsulLinkHealthCheck.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"); - } - } + 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 index f147a04..2a22e5a 100644 --- 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 @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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; @@ -29,64 +26,57 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.class,OpenRestyHealthCheck.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"); - } - } + 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 index 0cd429b..16b874e 100644 --- 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 @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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; @@ -28,65 +25,58 @@ 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; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class RedisHealthCheckTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(RedisHealthCheckTest.class); - - @Before + private static final Logger LOGGER = LoggerFactory.getLogger(RedisHealthCheckTest.class); + + @Before public void setUpBeforeTest() throws Exception { } - - @SuppressWarnings("static-access") - @Test - public void testchecksuccess() - { + + @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"); - } - - } + 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 index 9f75b1b..4f3176b 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -26,13 +24,11 @@ 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; @@ -43,44 +39,44 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + 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.*"}) +@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(); + 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(); + @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); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -90,163 +86,162 @@ public class ApiRouteServiceWrapperTest { } }); } - - + + @Test - public void test_getApiRouteInstance_not_exist(){ - try { - apiRouteServiceWrapper.getApiRouteInstance("testForJunit", "v1","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + 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) { + 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()); - } - + 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()); - } - + 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); - } + 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); + 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()); - } - - + 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 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; + + 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 index acbecd1..d72c57c 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -25,13 +23,11 @@ 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; @@ -41,42 +37,42 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + 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.*"}) +@PrepareForTest({JedisUtil.class, RouteUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class CustomRouteServiceWrapperTest { - private static CustomRouteServiceWrapper customRouteServiceWrapper; - private static Comparator<CustomRouteInfo> customRouteComparator = null; - + private static CustomRouteServiceWrapper customRouteServiceWrapper; + private static Comparator<CustomRouteInfo> customRouteComparator = null; + @BeforeClass public static void setUpBeforeClass() throws Exception { - customRouteServiceWrapper=CustomRouteServiceWrapper.getInstance(); + 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(); + @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); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -86,123 +82,125 @@ public class CustomRouteServiceWrapperTest { } }); } - + @Test - public void test_getCustomRouteInstance_not_exist(){ - try { - customRouteServiceWrapper.getCustomRouteInstance("/testForJunit","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + 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 { + 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) { + 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()); - } - + 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()); - } - + 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); - } + 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 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; + + 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 index 93f8b60..e7b0e4c 100644 --- 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 @@ -1,23 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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 io.dropwizard.jetty.HttpConnectorFactory; -import io.dropwizard.server.SimpleServerFactory; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -27,18 +22,12 @@ 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; @@ -50,207 +39,185 @@ 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; +import io.dropwizard.jetty.HttpConnectorFactory; +import io.dropwizard.server.SimpleServerFactory; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + @RunWith(PowerMockRunner.class) -@PrepareForTest({ JedisUtil.class, RedisAccessWrapper.class, ConfigUtil.class, - Http.class, InitRouteServiceWrapper.class }) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*" }) +@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()); - } + 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 index 55759b8..8a5ceca 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -25,13 +23,11 @@ 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; @@ -41,42 +37,42 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + 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.*"}) +@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(); + 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(); + @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); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -86,127 +82,125 @@ public class IuiRouteServiceWrapperTest { } }); } - + @Test - public void test_getIuiRouteInstance_not_exist(){ - try { - iuiRouteServiceWrapper.getIuiRouteInstance("testForJunit","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + 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) { + 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()); - } - + 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()); - } - + 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); - } + 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 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; + + 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 index a32cccc..516c5ed 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -32,8 +30,6 @@ 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; @@ -41,269 +37,266 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + 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.*"}) +@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(); + 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.saveMicroServiceInstance(microServiceFullInfo, false, "", ""); - MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); - Assert.assertEquals(microServiceFullInfo,dbMicroServiceFullInfo ); + microServiceWrapper.getMicroServiceInstance("testForJunit", "v1"); + Assert.fail("should not process to here."); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } - - } - - @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_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_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()); + + @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()); + } + } - try { - microServiceWrapper.deleteMicroService("testService2","v1"); - microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + + @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()); + } + } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); + + + + @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()); + + @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); + + } } - - //删除不存在实例 - try { - microServiceWrapper.deleteMicroServiceInstance("testService","v2","127.0.0.1","8989"); + + @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); + + } + } - 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()); + + } - - 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"); + + 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; } - catch(Exception e){ - Assert.fail("throw exception means error occured!" + e.getMessage()); + + 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; } - - 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()); + + 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; } - 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 index fcec469..71e6a84 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend; @@ -24,9 +22,6 @@ 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; @@ -44,121 +39,109 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@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); - - } + 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 index f22af71..e62d536 100644 --- 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 @@ -1,39 +1,34 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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); + @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); - } + 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 index 32167ca..a5718a1 100644 --- 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 @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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()); - } + @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 index 3daa261..c0cf337 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -19,9 +17,6 @@ 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; @@ -36,33 +31,32 @@ 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)); - - } + @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 index 0ee1e17..68f2fcf 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -34,52 +32,47 @@ 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)); - - } + @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 index a461fb9..2225eb2 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -20,38 +18,38 @@ 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 + @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)); - - } + + @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 index 77465fb..a44f587 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -31,99 +29,94 @@ 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)); - - } + + @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 index 50e2023..548639e 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -30,8 +28,6 @@ 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; @@ -47,107 +43,95 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@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(); - } - + 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 index ae8fa3b..641c4c7 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -49,123 +47,109 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@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(); - } + 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 index 9c37213..1c46d33 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.expose; @@ -31,31 +29,28 @@ 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>(); + @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(); + // 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); + 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); + 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); + WriteBufferHandler<List<ServiceHealth>> handler = + new WriteBufferHandler<List<ServiceHealth>>(ServiceData.DataType.service); - handler.handle(object); + 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 index 8c1f675..787a008 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.model.health; @@ -26,44 +24,39 @@ 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(); + @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(); + 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(); + ImmutableServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service).node(node) + .addChecks(healthCheck0).addChecks(healthCheck1, healthCheck2).build(); - Assert.assertNotNull(serviceHealth0.getNode()); - Assert.assertNotNull(serviceHealth0.getChecks()); - /* ############################################################### */ + 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)); - } + 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 index 42908bc..62724e5 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.model.health; @@ -20,28 +18,24 @@ 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()); + @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); + 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)); + Assert.assertFalse(service0.equals(service1)); - System.out.println(service1.hashCode()); + System.out.println(service1.hashCode()); - ImmutableService service2 = ImmutableService.builder().from(service1) - .build(); - Assert.assertEquals("new_id", service2.getId()); - } + 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 index acf72cc..086f0f0 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.consulextend.util; @@ -28,7 +26,6 @@ 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; @@ -39,57 +36,53 @@ 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); - } + 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 index 1260c5f..931c09d 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.queue; @@ -55,139 +53,133 @@ 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.*"}) +@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(); + private static QueueManager queueManager; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + queueManager = QueueManager.getInstance(); + putInServiceListQueue(); + putInServiceQueue4Update(); + } - - } - - - 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(); + + @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]); + } + }); } - 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); + + + + 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(); + } + } - } - - 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); + + + 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 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); + + + + 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 index 70b8441..76ad8f8 100644 --- 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 @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +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.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ 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 com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@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{ + public static void setUp() throws Exception { apiRouteService = ApiRouteService.getInstance(); apiRouteComparator = new Comparator<ApiRouteInfo>() { @Override @@ -61,11 +63,12 @@ public class ApiRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(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() { @@ -75,17 +78,18 @@ public class ApiRouteServiceTest { } }); } + @Test - public void testGetApiRouteInstance_key_not_exist(){ + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetApiRouteInstance_key_exist(){ + public void testGetApiRouteInstance_key_exist() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -94,18 +98,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveApiRouteService2Redis(){ + public void testSaveApiRouteService2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -114,18 +118,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveApiRouteService2Redis2(){ + public void testSaveApiRouteService2Redis2() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("test26msb"); apirouteInfo.setVersion("v1"); @@ -134,18 +138,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.151.26","443")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.151.26", "443")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:test26msb:v1"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteApiRouteService2Redis(){ + public void testDeleteApiRouteService2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -154,20 +158,20 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateApiRouteStatus2Redis(){ + public void testUpdateApiRouteStatus2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -176,15 +180,15 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + 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"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -198,7 +202,7 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + apirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); apirouteInfo2.setServiceName("testapi"); @@ -208,10 +212,10 @@ public class ApiRouteServiceTest { apirouteInfo2.setUseOwnUpstream("0"); apirouteInfo2.setVisualRange("0");; apirouteInfo.setEnable_ssl(true); - apirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + 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"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo2, "msb:routing:api:testapi:v2"); List<ApiRouteInfo> expected = new ArrayList<>(); expected.add(apirouteInfo); @@ -234,7 +238,7 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + apirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); apirouteInfo2.setServiceName("testapi"); @@ -244,23 +248,23 @@ public class ApiRouteServiceTest { 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"); + 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()); + 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"); + 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"); + 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 index 87c295f..1e11c78 100644 --- 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 @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +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.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ 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 com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@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{ + public static void setUp() throws Exception { customRouteService = CustomRouteService.getInstance(); customRouteComparator = new Comparator<CustomRouteInfo>() { @Override @@ -59,11 +61,12 @@ public class CustomRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(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() { @@ -73,17 +76,18 @@ public class CustomRouteServiceTest { } }); } + @Test - public void testGetCustomRouteInstance_key_not_exist(){ + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetCustomRouteInstance_key_exist(){ + public void testGetCustomRouteInstance_key_exist() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -91,18 +95,18 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveCustomRouteService2Redis(){ + public void testSaveCustomRouteService2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -110,18 +114,18 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveCustomRouteService2Redis_urlIsSlash(){ + public void testSaveCustomRouteService2Redis_urlIsSlash() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -129,19 +133,19 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteCustomRouteService2Redis(){ + public void testDeleteCustomRouteService2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -149,7 +153,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); @@ -157,12 +161,12 @@ public class CustomRouteServiceTest { 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateCustomRouteStatus2Redis(){ + public void testUpdateCustomRouteStatus2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -170,7 +174,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); @@ -178,7 +182,7 @@ public class CustomRouteServiceTest { 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -191,7 +195,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + customrouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); customrouteInfo2.setServiceName("testcustom2"); @@ -200,7 +204,7 @@ public class CustomRouteServiceTest { customrouteInfo2.setUseOwnUpstream("0"); customrouteInfo2.setVisualRange("0");; customrouteInfo.setEnable_ssl(true); - customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + 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"); @@ -225,7 +229,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + customrouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); customrouteInfo2.setServiceName("testcustom2"); @@ -234,12 +238,12 @@ public class CustomRouteServiceTest { customrouteInfo2.setUseOwnUpstream("0"); customrouteInfo2.setVisualRange("0");; customrouteInfo.setEnable_ssl(true); - customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + 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(2, customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); + assertEquals(2, customRouteService.deleteMultiCustomRouteService2Redis("msb:routing:custom:*")); assertEquals(0, customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); } 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 index bd4957e..213c3d6 100644 --- 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 @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +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.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ 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 com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@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{ + public static void setUp() throws Exception { iuiRouteService = IuiRouteService.getInstance(); iuiRouteComparator = new Comparator<IuiRouteInfo>() { @Override @@ -59,11 +61,12 @@ public class IuiRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(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() { @@ -73,17 +76,18 @@ public class IuiRouteServiceTest { } }); } + @Test - public void testGetIuiRouteInstance_key_not_exist(){ + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetIuiRouteInstance_key_exist(){ + public void testGetIuiRouteInstance_key_exist() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -91,18 +95,18 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveIuiRouteService2Redis(){ + public void testSaveIuiRouteService2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -110,18 +114,18 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteIuiRouteService2Redis(){ + public void testDeleteIuiRouteService2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -129,20 +133,20 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateIuiRouteStatus2Redis(){ + public void testUpdateIuiRouteStatus2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -150,15 +154,15 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); assertEquals("1", iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui").getStatus()); - iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:testiui","0"); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -171,7 +175,7 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + iuirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); iuirouteInfo2.setServiceName("testiui2"); @@ -180,10 +184,10 @@ public class IuiRouteServiceTest { iuirouteInfo2.setUseOwnUpstream("0"); iuirouteInfo2.setVisualRange("0");; iuirouteInfo.setEnable_ssl(true); - iuirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + 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"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2, "msb:routing:iui:testiui2"); List<IuiRouteInfo> expected = new ArrayList<>(); expected.add(iuirouteInfo); @@ -205,7 +209,7 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + iuirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); iuirouteInfo2.setServiceName("testiui2"); @@ -214,23 +218,23 @@ public class IuiRouteServiceTest { 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"); + 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()); + 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"); + iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:notexistservice", "0"); } @Test(expected = Exception.class) public void testSaveIuiRouteService2Redis_null() throws Exception { - iuiRouteService.saveIuiRouteService2Redis(null,"msb:routing:iui:null"); + 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 index aa5db78..6e7200d 100644 --- 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 @@ -1,21 +1,33 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.mockito.PowerMockito.when; + +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.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,31 +35,27 @@ 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 com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; -import static org.powermock.api.mockito.PowerMockito.when; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@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{ + public static void setUp() throws Exception { microServiceFullService = MicroServiceFullService.getInstance(); serviceComparator = new Comparator<MicroServiceFullInfo>() { @Override @@ -60,11 +68,12 @@ public class MicroServiceFullServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -76,15 +85,16 @@ public class MicroServiceFullServiceTest { } @Test - public void testExistsMicroServiceInstance_notExist(){ + public void testExistsMicroServiceInstance_notExist() { try { assertFalse(microServiceFullService.existsMicroServiceInstance("notExist", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } + @Test - public void testExistsMicroServiceInstance_Exist(){ + public void testExistsMicroServiceInstance_Exist() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -94,20 +104,20 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveMicroServiceInfo2Redis(){ + public void testSaveMicroServiceInfo2Redis() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -117,7 +127,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); @@ -125,12 +135,12 @@ public class MicroServiceFullServiceTest { assertEquals(microServiceFullInfo, actual); } catch (Exception e) { e.printStackTrace(); - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteMicroService(){ + public void testDeleteMicroService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -140,21 +150,21 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + 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"); + microServiceFullService.deleteMicroService("testService", "v1"); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateMicroServiceStatus(){ + public void testUpdateMicroServiceStatus() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -164,20 +174,20 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","v1").getStatus()); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllMicroServiceKey(){ + public void testGetAllMicroServiceKey() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -187,7 +197,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -199,7 +209,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(false); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.88","8081")); + nodeSet2.add(new Node("10.74.148.88", "8081")); microServiceFullInfo2.setNodes(nodeSet2); MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); @@ -211,7 +221,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + nodeSet3.add(new Node("10.74.148.89", "8080")); microServiceFullInfo3.setNodes(nodeSet3); try { @@ -220,19 +230,19 @@ public class MicroServiceFullServiceTest { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); Set<String> result = microServiceFullService.getAllMicroServiceKey(); - final Set<String> expected =new HashSet<String>(); + 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllVersionsOfTheService(){ + public void testGetAllVersionsOfTheService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -242,7 +252,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -254,7 +264,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(false); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.88","8081")); + nodeSet2.add(new Node("10.74.148.88", "8081")); microServiceFullInfo2.setNodes(nodeSet2); MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); @@ -266,7 +276,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + nodeSet3.add(new Node("10.74.148.89", "8080")); microServiceFullInfo3.setNodes(nodeSet3); try { @@ -281,17 +291,17 @@ public class MicroServiceFullServiceTest { expected.add(microServiceFullInfo); expected.add(microServiceFullInfo3); - Collections.sort(expected,serviceComparator); - Collections.sort(result,serviceComparator); + Collections.sort(expected, serviceComparator); + Collections.sort(result, serviceComparator); assertEquals(expected, result); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllMicroServicesInstances(){ + public void testGetAllMicroServicesInstances() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -301,7 +311,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -313,7 +323,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(true); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.89","8080")); + nodeSet2.add(new Node("10.74.148.89", "8080")); microServiceFullInfo2.setNodes(nodeSet2); try { @@ -325,17 +335,17 @@ public class MicroServiceFullServiceTest { expected.add(microServiceFullInfo2); List<MicroServiceFullInfo> result = microServiceFullService.getAllMicroServiceInstances(); Collections.sort(expected, serviceComparator); - Collections.sort(result,serviceComparator ); + Collections.sort(result, serviceComparator); assertEquals(expected, result); } catch (Exception e) { e.printStackTrace(); - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteMultiMicroService(){ + public void testDeleteMultiMicroService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -345,7 +355,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); @@ -358,34 +368,36 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + 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()); + // 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(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void tesGetMicroServiceInstance_notExist(){ + public void tesGetMicroServiceInstance_notExist() { try { - assertNull(microServiceFullService.getMicroServiceInstance("notExist","v1")); + assertNull(microServiceFullService.getMicroServiceInstance("notExist", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } + @Test - public void tesExistsGetUpdateDeleteMicroServiceStatus_versionNull(){ + public void tesExistsGetUpdateDeleteMicroServiceStatus_versionNull() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion(""); @@ -395,29 +407,29 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { - //test null + // test null assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","null").getStatus()); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService", "null").getStatus()); microServiceFullService.updateMicroServiceStatus("testService", "null", "0"); assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", "null").getStatus()); - microServiceFullService.deleteMicroService("testService","null"); + microServiceFullService.deleteMicroService("testService", "null"); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); - //test String "null" + // test String "null" assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService",null).getStatus()); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService", null).getStatus()); microServiceFullService.updateMicroServiceStatus("testService", null, "0"); assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", null).getStatus()); - microServiceFullService.deleteMicroService("testService",null); + microServiceFullService.deleteMicroService("testService", null); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } 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 index 1df3643..78fed80 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.serviceListener; @@ -39,7 +37,6 @@ 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; @@ -49,633 +46,619 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + 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,}) +@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()); + 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_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_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_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_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_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()); + + @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); + } + } - - 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()); + + + @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); + } + } - - 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()); + + + @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()); + } + } - - 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()); + + + 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; } - - 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()); + + 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; } - - 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()); + + + 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; } - - 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()); + + 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; } - - 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()); + + 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; } - - 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()); + + 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; } - - 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 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; } - - } - - - 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 index 07f2b86..6a3bfb7 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -20,57 +18,56 @@ 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_concat() { + Object[] str1 = new String[] {"test1", "test2"}; + Object[] str2 = new String[] {"test3"}; + Object[] str3 = CommonUtil.concat(str1, str2); - @Test - public void test_containStr() { - String value = "1"; - String array[] = {"1", "2"}; - Assert.assertTrue(CommonUtil.contain(array, value)); - Assert.assertFalse(CommonUtil.contain(array, "3")); - } + Assert.assertEquals(3, str3.length); + } - @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_containStr() { + String value = "1"; + String array[] = {"1", "2"}; + Assert.assertTrue(CommonUtil.contain(array, value)); + Assert.assertFalse(CommonUtil.contain(array, "3")); + } - @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_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_getDiffrent() { - Set<String> list1 = new HashSet<String>(); - list1.add("test1"); - list1.add("test2"); + @Test + public void test_containStrArray() { + Assert.assertFalse(CommonUtil.contain("0,1,2", "3")); + Assert.assertTrue(CommonUtil.contain("0,1,2", "1")); + } - Set<String> list2 = new HashSet<String>(); - list2.add("test2"); - list2.add("test3"); + @Test + public void test_getDiffrent() { + Set<String> list1 = new HashSet<String>(); + list1.add("test1"); + list1.add("test2"); - Set<String> diff = CommonUtil.getDiffrent(list1, list2); - Assert.assertEquals(1, diff.size()); - Assert.assertTrue(diff.contains("test3")); - } + 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 index c32b6c0..51a06df 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -24,7 +22,6 @@ 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; @@ -33,197 +30,196 @@ import org.powermock.modules.junit4.PowerMockRunner; @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_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(); + } } - } - - @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 index 61c19ad..338ab48 100644 --- 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 @@ -1,44 +1,33 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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); - }*/ - } + 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 index cff0b42..baf8b2a 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -21,74 +19,72 @@ 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){ + 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){ + 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 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()); - } + 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); - } + 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 index 91fbe32..0004aad 100644 --- 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 @@ -1,35 +1,32 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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.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); - + @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 index bede4ff..2b622a4 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -20,41 +18,38 @@ 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)); - - } + @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 index 2d5c5c5..76a0c7d 100644 --- 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 @@ -1,96 +1,94 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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(){ + 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(){ + 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")); + public void test_PortRegExpTest() { + Assert.assertTrue(RegExpTestUtil.portRegExpTest("80")); Assert.assertFalse(RegExpTestUtil.portRegExpTest("898989")); } - - + + @Test - public void test_VersionRegExpTest(){ + public void test_VersionRegExpTest() { Assert.assertTrue(RegExpTestUtil.versionRegExpTest("v1")); Assert.assertFalse(RegExpTestUtil.versionRegExpTest("23")); } - - - + + + @Test - public void test_urlRegExpTest(){ + public void test_urlRegExpTest() { Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/test")); Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/")); Assert.assertFalse(RegExpTestUtil.urlRegExpTest("test")); } - - + + @Test - public void test_apiRouteUrlRegExpTest(){ + public void test_apiRouteUrlRegExpTest() { Assert.assertTrue(RegExpTestUtil.apiRouteUrlRegExpTest("/api/test/v1")); Assert.assertFalse(RegExpTestUtil.apiRouteUrlRegExpTest("/test")); } - - - + + + @Test - public void test_iuiRouteUrlRegExpTest(){ + 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")); + 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")); + 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 index 08fcf6c..02fa9f3 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -34,340 +32,344 @@ import org.powermock.modules.junit4.PowerMockRunner; @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_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_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_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); + } - @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); + } } - - 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_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_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() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - - 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_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_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_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_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_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_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_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_getVisualRangeByRouter() { + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); + Assert.assertEquals("1", RouteUtil.getVisualRangeByRouter("1")); + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0")); + + } - } - - @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_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_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_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_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_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_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_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_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); + + + @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 index 9c9d4b1..5759014 100644 --- 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 @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 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 + * 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 + * 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. + * 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; @@ -45,180 +43,173 @@ 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")); - - - } + @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")); + + + } |