diff options
Diffstat (limited to 'src/test/java/org/onap/dmaap/mr')
61 files changed, 4147 insertions, 3020 deletions
diff --git a/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java index 549c541..3b1a9ac 100644 --- a/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,46 +22,25 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import org.onap.dmaap.mr.client.HostSelector; +import static org.junit.Assert.assertTrue; public class HostSelectorTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - - @Test - public void testSelectBaseHost() { - - HostSelector selector = new HostSelector("host"); - - selector.selectBaseHost(); - assertTrue(true); - - } + @Test + public void testSelectBaseHost() { - @Test - public void testReportReachabilityProblem() { - - HostSelector selector = new HostSelector("host"); - - selector.reportReachabilityProblem(100, null); - assertTrue(true); - + HostSelector selector = new HostSelector("host"); + selector.selectBaseHost(); + assertTrue(true); + } - } + @Test + public void testReportReachabilityProblem() { + HostSelector selector = new HostSelector("host"); + selector.reportReachabilityProblem(100, null); + assertTrue(true); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java index 1ed519a..56f341e 100644 --- a/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.client; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,16 +30,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) - +@SuiteClasses({HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java index 80f6ec2..e704e73 100644 --- a/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java @@ -5,13 +5,14 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,15 +23,14 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.util.ArrayList; import java.util.Collection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientBuilders; +import static org.junit.Assert.assertTrue; public class MRClientBuildersTest { diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java index e800671..2203373 100644 --- a/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java @@ -5,13 +5,14 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,15 +23,15 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class MRClientFactoryTest { @@ -71,177 +72,116 @@ public class MRClientFactoryTest { @Test public void testCreateConsumer3() { - MRClientFactory.createConsumer(hostSet, "testTopic", "filter"); assertTrue(true); - } @Test public void testCreateConsumer4() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22"); assertTrue(true); - } @Test public void testCreateConsumer5() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100); assertTrue(true); - } @Test public void testCreateConsumer6() { - MRClientFactory.createConsumer("hostList", "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); assertTrue(true); - } @Test public void testCreateConsumer7() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); assertTrue(true); - } @Test public void testCreateSimplePublisher() { - MRClientFactory.createSimplePublisher("hostList", "testTopic"); assertTrue(true); - } @Test public void testCreateBatchingPublisher1() { - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10); assertTrue(true); - } @Test public void testCreateBatchingPublisher2() { - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher3() { - MRClientFactory.createBatchingPublisher(hostArray, "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher4() { - - MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); + MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher5() { - MRClientFactory.createBatchingPublisher("host", "testTopic", "username", "password", 100, 10, true, "protocolFlag"); assertTrue(true); - } - @Test - public void testCreateBatchingPublisher6() { - - try { - MRClientFactory.createBatchingPublisher("/producer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateBatchingPublisher6() throws IOException { + MRClientFactory.createBatchingPublisher("/producer"); } - @Test - public void testCreateBatchingPublisher7() { - - try { - MRClientFactory.createBatchingPublisher("/producer", true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateBatchingPublisher7() throws IOException { + MRClientFactory.createBatchingPublisher("/producer", true); } @Test public void testCreateIdentityManager() { - MRClientFactory.createIdentityManager(hostSet, "apikey", "apisecret"); - assertTrue(true); - } @Test public void testCreateTopicManager() { - MRClientFactory.createTopicManager(hostSet, "apikey", "apisecret"); - assertTrue(true); - } - @Test - public void testCreateConsumer8() { - - try { - MRClientFactory.createConsumer("/consumer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateConsumer8() throws IOException { + MRClientFactory.createConsumer("/consumer"); } @Test public void testCreateConsumer9() { - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", "protocolFlag", "/consumer", 1, 2); - assertTrue(true); - } @Test public void testCreateConsumer10() { - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", 1, 2, "protocolFlag", "/consumer"); - assertTrue(true); - } - + @Test public void test$testInject() { - MRClientFactory.$testInject(null); assertTrue(true); - } }
\ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mr/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java index 2cc2c10..92c03cb 100644 --- a/src/test/java/org/onap/dmaap/mr/client/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java index 5d63759..ca4fb3b 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2018 IBM Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +19,10 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client.impl; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import java.util.Properties; - -import javax.ws.rs.client.Invocation.Builder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; +package org.onap.dmaap.mr.client.impl; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -40,6 +32,16 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + public class DMaapClientUtilTest { @Mock Response response; @@ -47,56 +49,56 @@ public class DMaapClientUtilTest { Builder builder; @Mock WebTarget target; - private ClientConfig config=null; + private ClientConfig config = null; @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(this); } - + @Test public void testGetTarget() { - WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(),"testpath"); - + WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(), "testpath"); + assertEquals("testpath", actual.getUri().getPath()); } - + @Test public void testGetTargetWithParams() { - WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(),"testpath", "testuser", "testpassword"); - + WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(), "testpath", "testuser", "testpassword"); + assertEquals("testpath", actual.getUri().getPath()); } - + @Test public void testGetResponsewtCambriaAuth() { - Mockito.when(target.request()).thenReturn(builder); - Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); - Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); - Mockito.when(builder.get()).thenReturn(response); - + Mockito.when(target.request()).thenReturn(builder); + Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); + Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); + Mockito.when(builder.get()).thenReturn(response); + Response actual = DmaapClientUtil.getResponsewtCambriaAuth(target, "testuser", "testpassword"); assertEquals(response, actual); verify(target).request(); verify(builder, times(2)).header((String) any(), any()); } - + @Test public void testSetHttpClientProperties() { - Properties properties = new Properties(); - properties.setProperty(ClientProperties.PROXY_URI, "http://localhost:1234"); - ClientConfig cConfig = DmaapClientUtil.getClientConfig(properties); + Properties properties = new Properties(); + properties.setProperty(ClientProperties.PROXY_URI, "http://localhost:1234"); + ClientConfig cConfig = DmaapClientUtil.getClientConfig(properties); - assertEquals(cConfig.getConnectorProvider().getClass().getSimpleName(), "ApacheConnectorProvider"); + assertEquals("ApacheConnectorProvider", cConfig.getConnectorProvider().getClass().getSimpleName()); } - private ClientConfig getClientConfig(){ - if(config==null){ - config=DmaapClientUtil.getClientConfig(null); - } - return config; - - } + private ClientConfig getClientConfig() { + if (config == null) { + config = DmaapClientUtil.getClientConfig(null); + } + return config; + + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java index dc2c5ff..9d47192 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +19,10 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.verify; - -import java.net.MalformedURLException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; +package org.onap.dmaap.mr.client.impl; import org.apache.http.HttpException; import org.glassfish.jersey.client.ClientConfig; @@ -50,447 +39,457 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import java.net.MalformedURLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; + @RunWith(PowerMockRunner.class) @PowerMockIgnore({"org.apache.http.conn.ssl.*", "jdk.internal.reflect.*"}) -@PrepareForTest({ DmaapClientUtil.class }) +@PrepareForTest({DmaapClientUtil.class}) public class MRBaseClientTest { - // @InjectMocks - private MRBaseClient mrBaseClient; - private Collection<String> hosts = new HashSet<>(Arrays.asList("localhost:8080")); - private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; - private ClientConfig config=null; - - @Before - public void setup() throws MalformedURLException { - mrBaseClient = new MRBaseClient(hosts, clientSignature); - PowerMockito.mockStatic(DmaapClientUtil.class); - } - - @Test - public void testGet() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); - - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertEquals(200, result.getInt("status")); - assertEquals("test", result.getString("test")); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - } - - @Test - public void testGet_403() throws JSONException, HttpException { - ResponseBuilder responseBuilder = Response.status(403); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertEquals(403, result.getInt("status")); - } - - @Test - public void testGet_basicauth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + // @InjectMocks + private MRBaseClient mrBaseClient; + private Collection<String> hosts = new HashSet<>(Arrays.asList("localhost:8080")); + private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; + private ClientConfig config = null; + + @Before + public void setup() throws MalformedURLException { + mrBaseClient = new MRBaseClient(hosts, clientSignature); + PowerMockito.mockStatic(DmaapClientUtil.class); + } + + @Test + public void testGet() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); + + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); + + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertEquals(200, result.getInt("status")); + assertEquals("test", result.getString("test")); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + } + + @Test + public void testGet_403() throws JSONException, HttpException { + ResponseBuilder responseBuilder = Response.status(403); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertEquals(403, result.getInt("status")); + } + + @Test + public void testGet_basicauth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); - Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAAF"); + assertEquals(200, result.getInt("status")); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + + } - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAAF"); - assertEquals(200, result.getInt("status")); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - - } + @Test(expected = HttpException.class) + public void testGet_error() throws JSONException, HttpException { - @Test(expected = HttpException.class) - public void testGet_error() throws JSONException, HttpException { + ResponseBuilder responseBuilder = Response.ok(); + Mockito.when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - ResponseBuilder responseBuilder = Response.ok(); - Mockito.when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + mrBaseClient.get("/path", null, null, "HTTPAUTH"); + } - mrBaseClient.get("/path", null, null, "HTTPAUTH"); - } + @Test + public void testGet_wrongjson() throws JSONException, HttpException { - @Test - public void testGet_wrongjson() throws JSONException, HttpException { + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("[["); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("[["); - Mockito.when(response.getHeaders()).thenReturn(map); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + } - mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - } + @Test + public void testGetResponse() throws JSONException, HttpException { - @Test - public void testGetResponse() throws JSONException, HttpException { + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); + mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); - } + } - @Test - public void testGetResponse_aaf() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); - - mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); - assertTrue(true); + @Test + public void testGetResponse_aaf() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testGetResponse_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); - mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); - } + mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); + assertTrue(true); - @Test - public void testAuthResponse() throws JSONException, HttpException { + } - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + @Test(expected = HttpException.class) + public void testGetResponse_error() throws JSONException, HttpException { - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); + } - mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + @Test + public void testAuthResponse() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testAuthResponsee_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); + mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - } + } - @Test - public void testPostAuth() throws JSONException, HttpException { + @Test(expected = HttpException.class) + public void testAuthResponsee_error() throws JSONException, HttpException { - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); + } - mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") - .setData( new String("{\"test\":\"test\"}").getBytes()) - .setContentType("application/json") - .setAuthKey("username") - .setAuthDate("password") - .setUsername("username") - .setPassword("password") - .setProtocolFlag("HTTPAUTH")); - assertTrue(true); + @Test + public void testPostAuth() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testPostAuth_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") - .setData( new String("{\"test\":\"test\"}").getBytes()) + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); + + mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") + .setData(("{\"test\":\"test\"}").getBytes()) + .setContentType("application/json") + .setAuthKey("username") + .setAuthDate("password") + .setUsername("username") + .setPassword("password") + .setProtocolFlag("HTTPAUTH")); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPostAuth_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") + .setData(("{\"test\":\"test\"}").getBytes()) .setContentType("application/json") .setAuthKey(null) .setAuthDate(null) - .setUsername(null) + .setUsername(null) .setPassword(null) .setProtocolFlag("HTTPAUTH")); - } + } + + @Test + public void testGetNoAuthResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetNoAuthResponse() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"))).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"))).thenReturn(response); + @Test + public void testPost() throws JSONException, HttpException { - mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPost() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"), ("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.post("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", "username", + "password", "HTTPAUTH"); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + @Test(expected = HttpException.class) + public void testPost_error() throws JSONException, HttpException { - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", - "password", "HTTPAUTH"); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.post("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", null, null, + "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPost_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testPostAuthwithResponse() throws JSONException, HttpException { - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, - "HTTPAUTH"); + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPostAuthwithResponse() throws JSONException, HttpException { + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.postAuthwithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); + @Test(expected = HttpException.class) + public void testPostAuthwithResponse_error() throws JSONException, HttpException { - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.postAuthwithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + null, null, null, null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPostAuthwithResponse_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testPostWithResponse() throws JSONException, HttpException { - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - null, null, null, null, "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPostWithResponse() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"), ("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.postWithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + @Test(expected = HttpException.class) + public void testPostWithResponse_error() throws JSONException, HttpException { - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.postWithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", null, + null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPostWithResponse_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testGetAuth() throws JSONException, HttpException { - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, - null, "HTTPAUTH"); + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetAuth() throws JSONException, HttpException { + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); + mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + } - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + @Test(expected = HttpException.class) + public void testGetAuth_error() throws JSONException, HttpException { - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); - mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testGetAuth_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testGetNoAuth() throws JSONException, HttpException { - mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetNoAuth() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"))).thenReturn(response); + mrBaseClient.getNoAuth("/path"); + assertTrue(true); - Response response = Mockito.mock(Response.class); - MultivaluedMap<String, Object> map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + } - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"))).thenReturn(response); - mrBaseClient.getNoAuth("/path"); - assertTrue(true); + @Test + public void testGetHTTPErrorResponseMessage() { + assertEquals("testtest", mrBaseClient.getHTTPErrorResponseMessage("<body>testtest</body>")); - } + } + @Test + public void getGTTPErrorResponseCode() { + assertEquals("500", mrBaseClient.getHTTPErrorResponseCode("<title>500</title>")); + } - @Test - public void testGetHTTPErrorResponseMessage() { - assertEquals("testtest", mrBaseClient.getHTTPErrorResponseMessage("<body>testtest</body>")); - } + private ClientConfig getClientConfig() { + if (config == null) { + config = DmaapClientUtil.getClientConfig(null); + } + return config; - @Test - public void getGTTPErrorResponseCode() { - assertEquals("500", mrBaseClient.getHTTPErrorResponseCode("<title>500</title>")); - } - - - - private ClientConfig getClientConfig(){ - if(config==null){ - config=DmaapClientUtil.getClientConfig(null); - } - return config; - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java index 3d1e3d0..4d8811f 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +19,39 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import org.junit.Before; +import org.junit.Test; + import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; -import org.junit.Before; -import org.junit.Test; - public class MRBatchPublisherTest { - - private Collection<String> hosts=new HashSet<>(Arrays.asList("/test")); - private MRBatchPublisher mrBatchPublisher=new MRBatchPublisher(hosts, "topic", 2, 20, true); - - - @Before - public void setup(){ - - - } - - @Test(expected = Test.None.class /* no exception expected */) - public void testSend() throws IOException{ - mrBatchPublisher.send("testmessage"); - } - - @Test(expected = Test.None.class /* no exception expected */) - public void testClose() throws IOException{ - mrBatchPublisher.close(); - } + + private Collection<String> hosts = new HashSet<>(Arrays.asList("/test")); + private MRBatchPublisher mrBatchPublisher = new MRBatchPublisher(hosts, "topic", 2, 20, true); + + + @Before + public void setup() { + + + } + + @Test(expected = Test.None.class /* no exception expected */) + public void testSend() throws IOException { + mrBatchPublisher.send("testmessage"); + } + + @Test(expected = Test.None.class /* no exception expected */) + public void testClose() throws IOException { + mrBatchPublisher.close(); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java index d912f9d..09fc2a8 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,125 +19,112 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import junit.framework.TestCase; +import org.apache.http.HttpHost; +import org.junit.Test; + import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; -import junit.framework.TestCase; - -import org.apache.http.HttpHost; -import org.junit.Test; - -public class MRConstantsTest extends TestCase -{ - @Test - public void testPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocol () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocolAndPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPortAndEscapedTopic () throws IOException - { - final String rawTopic = "bar?bell"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar%3Fbell", result ); - } - - @Test - public void testConsumerPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String rawGroup = "group"; - final String rawId = "id"; - final String result = MRConstants.makeConsumerUrl ( rawTopic, rawGroup, rawId ); - assertEquals ( "/events/" + "bar/group/id", result ); - } - - @Test - public void testCreateHostList () - { - final ArrayList<String> in = new ArrayList<String> (); - in.add ( "foo" ); - in.add ( "bar" ); - in.add ( "baz:80" ); - - final Collection<HttpHost> hosts = MRConstants.createHostsList ( in ); - assertEquals ( 3, hosts.size () ); - - final Iterator<HttpHost> it = hosts.iterator (); - final HttpHost first = it.next (); - assertEquals ( MRConstants.STD_MR_SERVICE_PORT, first.getPort () ); - assertEquals ( "foo", first.getHostName () ); - - final HttpHost second = it.next (); - assertEquals ( MRConstants.STD_MR_SERVICE_PORT, second.getPort () ); - assertEquals ( "bar", second.getHostName () ); - - final HttpHost third = it.next (); - assertEquals ( 80, third.getPort () ); - assertEquals ( "baz", third.getHostName () ); - } - - private static final String[][] hostTests = - { - { "host", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, - { ":oops", null, "-1" }, - { "host:1.3", null, "-1" }, - { "host:13", "host", "13" }, - { "host:", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, - }; - - @Test - public void testHostParse () - { - for ( String[] test : hostTests ) - { - final String hostIn = test[0]; - final String hostOut = test[1]; - final int portOut = Integer.parseInt ( test[2] ); - - try - { - final HttpHost hh = MRConstants.hostForString ( hostIn ); - assertEquals ( hostOut, hh.getHostName () ); - assertEquals ( portOut, hh.getPort () ); - } - catch ( IllegalArgumentException x ) - { - assertEquals ( -1, portOut ); - } - } - } +public class MRConstantsTest extends TestCase { + @Test + public void testPlainHost() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithProtocol() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithProtocolAndPort() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithPort() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithPortAndEscapedTopic() throws IOException { + final String rawTopic = "bar?bell"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar%3Fbell", result); + } + + @Test + public void testConsumerPlainHost() throws IOException { + final String rawTopic = "bar"; + final String rawGroup = "group"; + final String rawId = "id"; + final String result = MRConstants.makeConsumerUrl(rawTopic, rawGroup, rawId); + assertEquals("/events/" + "bar/group/id", result); + } + + @Test + public void testCreateHostList() { + final ArrayList<String> in = new ArrayList<String>(); + in.add("foo"); + in.add("bar"); + in.add("baz:80"); + + final Collection<HttpHost> hosts = MRConstants.createHostsList(in); + assertEquals(3, hosts.size()); + + final Iterator<HttpHost> it = hosts.iterator(); + final HttpHost first = it.next(); + assertEquals(MRConstants.STD_MR_SERVICE_PORT, first.getPort()); + assertEquals("foo", first.getHostName()); + + final HttpHost second = it.next(); + assertEquals(MRConstants.STD_MR_SERVICE_PORT, second.getPort()); + assertEquals("bar", second.getHostName()); + + final HttpHost third = it.next(); + assertEquals(80, third.getPort()); + assertEquals("baz", third.getHostName()); + } + + private static final String[][] hostTests = + { + {"host", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, + {":oops", null, "-1"}, + {"host:1.3", null, "-1"}, + {"host:13", "host", "13"}, + {"host:", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, + }; + + @Test + public void testHostParse() { + for (String[] test : hostTests) { + final String hostIn = test[0]; + final String hostOut = test[1]; + final int portOut = Integer.parseInt(test[2]); + + try { + final HttpHost hh = MRConstants.hostForString(hostIn); + assertEquals(hostOut, hh.getHostName()); + assertEquals(portOut, hh.getPort()); + } catch (IllegalArgumentException x) { + assertEquals(-1, portOut); + } + } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java index 52c7111..7b77a95 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,182 +19,181 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; +import junit.framework.TestCase; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.ProtocolType; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Properties; -import junit.framework.TestCase; - -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; - public class MRConsumerImplTest extends TestCase { - @Test - public void testNullFilter() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + @Test + public void testNullFilter() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid", url); - } - - @Test - public void testFilterWithNoTimeoutOrLimit() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid", url); + } + + @Test + public void testFilterWithNoTimeoutOrLimit() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("filter").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url); - } - - @Test - public void testTimeoutNoLimitNoFilter() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url); + } + + @Test + public void testTimeoutNoLimitNoFilter() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(30000) .setLimit(-1).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - 30000, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url); - } - - @Test - public void testNoTimeoutWithLimitNoFilter() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + 30000, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url); + } + + @Test + public void testNoTimeoutWithLimitNoFilter() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(100).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, 100); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?limit=100", url); - } - - @Test - public void testWithTimeoutWithLimitWithFilter() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, 100); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?limit=100", url); + } + + @Test + public void testWithTimeoutWithLimitWithFilter() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(1000) .setLimit(400).setFilter("f").setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - 1000, 400); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url); - } - - @Test - public void testFilterEncoding() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + 1000, 400); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url); + } + + @Test + public void testFilterEncoding() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url); - } - - @Test - public void testFetchWithReturnConsumerResponse() throws IOException { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath = "dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("routeFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - File outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - - MRClientFactory.prop=properties; + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url); + } + + @Test + public void testFetchWithReturnConsumerResponse() throws IOException { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("routeFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + File outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + + MRClientFactory.prop = properties; final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - c.setProps(properties); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - assertTrue(true); - } - - @Test - public void testFetch() throws Exception { - final LinkedList<String> hosts = new LinkedList<String>(); - hosts.add("localhost:8080"); - - - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath = "dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("routeFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - File outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - - MRClientFactory.prop=properties; + c.setProps(properties); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + assertTrue(true); + } + + @Test + public void testFetch() throws Exception { + final LinkedList<String> hosts = new LinkedList<String>(); + hosts.add("localhost:8080"); + + + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("routeFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + File outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + + MRClientFactory.prop = properties; final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - c.setProps(properties); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - } + c.setProps(properties); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java index ea9cab4..00f1278 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,110 +19,98 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; + import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.Set; -import org.junit.Before; -import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; public class MRMetaClientTest { - - //@Rule public WireMockRule wireMock = new WireMockRule(); - - @Before - public void setUp(){/* - wireMock.stubFor(get(urlEqualTo("/topics")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(get(urlEqualTo("/topics/topic1")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(post(urlEqualTo("/topics/create")) - .willReturn(aResponse().withStatus(200))); - */} - - @Test - public void getTopicsTest() - { - final Collection<String> hosts = new LinkedList<String> (); - hosts.add ( "localhost:" +3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - Set<String> setString=c.getTopics(); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(hosts); - - - // assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); - - } - - @Test - public void getTopicMetadataTest() { - final Collection<String> hosts = new LinkedList<String> (); - hosts.add ( "localhost:" + 3904 ); - - final String topic ="topic1"; - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - TopicInfo topicInfo=c.getTopicMetadata(topic); - } catch (IOException | HttpObjectNotFoundException e) { - e.printStackTrace(); - } - assertNotNull(topic); - - } - - @Test - public void testcreateTopic(){ - final Collection<String> hosts = new LinkedList<String> (); - hosts.add ( "localhost:" + 3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.createTopic("topic1", "testTopic", 1, 1); - } catch (IOException | HttpException e) { - e.printStackTrace(); - } - assertNotNull(hosts); - } - @Test - public void testupdateApiKey(){ - final Collection<String> hosts = new LinkedList<String> (); - hosts.add ( "localhost:" + 3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.updateCurrentApiKey("test@onap.com", "test email"); - }catch (HttpException e) { - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - catch (NullPointerException e) { - assertTrue(true); - } - - } - - + + @Test + public void getTopicsTest() { + final Collection<String> hosts = new LinkedList<String>(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + Set<String> setString = c.getTopics(); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(hosts); + + + //assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); + + } + + @Test + public void getTopicMetadataTest() { + final Collection<String> hosts = new LinkedList<String>(); + hosts.add("localhost:" + 3904); + + final String topic = "topic1"; + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + TopicInfo topicInfo = c.getTopicMetadata(topic); + } catch (IOException | HttpObjectNotFoundException e) { + e.printStackTrace(); + } + assertNotNull(topic); + + } + + @Test + public void testcreateTopic() { + final Collection<String> hosts = new LinkedList<String>(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.createTopic("topic1", "testTopic", 1, 1); + } catch (IOException | HttpException e) { + e.printStackTrace(); + } + assertNotNull(hosts); + } + + @Test + public void testupdateApiKey() { + final Collection<String> hosts = new LinkedList<String>(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.updateCurrentApiKey("test@onap.com", "test email"); + } catch (HttpException e) { + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java index af5ccd2..26fee9e 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,54 +19,56 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; import static org.junit.Assert.assertNotNull; public class MRSimplerBatchConsumerTest { - - File outFile; - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath="dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } - - @Test - public void testSend() throws IOException, InterruptedException { - - final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); - - try { - for(String msg : cc.fetch()){ - System.out.println(msg); - } - } catch (Exception e) { - System.err.println ( e.getClass().getName () + ": " + e.getMessage () ); - } - assertNotNull(cc); - - } - + + File outFile; + + @Before + public void setUp() throws Exception { + Properties properties = new Properties(); + properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws IOException, InterruptedException { + + final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); + + try { + for (String msg : cc.fetch()) { + System.out.println(msg); + } + } catch (Exception e) { + System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } + assertNotNull(cc); + + } + } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java index b2f8817..1ac22ef 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,302 +19,298 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; -import static org.junit.Assert.assertEquals; +import org.json.JSONObject; +import org.junit.Assert; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.onap.dmaap.mr.client.ProtocolType; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.IOException; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; -import org.json.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRPublisher.message; -import org.onap.dmaap.mr.client.response.MRPublisherResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import static org.junit.Assert.assertEquals; public class MRSimplerBatchPublisherTest { - File outFile; + File outFile; + + public void setUp(String contentType) throws Exception { + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + if (contentType != null) { + properties.put("contenttype", contentType); + } + outFile = new File(file.getParent() + "/producer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws Exception { + + setUp(null); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); + + } + + @Test + public void testSendBatchWithResponse() throws Exception { + + setUp(null); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); + + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + + } + + @Test + public void testSendBatchWithResponseConText() throws Exception { + + setUp("text/plain"); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); + + } + + @Test + public void testSendBatchWithResponseContCambria() throws Exception { - public void setUp(String contentType) throws Exception { - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); + setUp("application/cambria-zip"); - String routeFilePath = "dme2/preferredRoute.txt"; + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - if (contentType != null) { - properties.put("contenttype", contentType); - } - outFile = new File(file.getParent() + "/producer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - @Test - public void testSend() throws Exception { + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - setUp(null); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + @Test + public void testSendBatchWithResponseProtKey() throws Exception { - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + setUp(null); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - } + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - @Test - public void testSendBatchWithResponse() throws Exception { + } - setUp(null); + @Test + public void testSendBatchWithResponseProtAaf() throws Exception { - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + setUp(null); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - } + } - @Test - public void testSendBatchWithResponseConText() throws Exception { + @Test + public void testSendBatchWithResponseProtNoAuth() throws Exception { - setUp("text/plain"); + setUp(null); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + final List<Message> stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + } - } + @Test + public void testSendBatchWithResponsecontypeText() throws Exception { - @Test - public void testSendBatchWithResponseContCambria() throws Exception { + setUp("text/plain"); - setUp("application/cambria-zip"); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", "payload"); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + } - } + @Test + public void testSendBatchWithResponsecontypeCambria() throws Exception { - @Test - public void testSendBatchWithResponseProtKey() throws Exception { + setUp("application/cambria-zip"); - setUp(null); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", "payload"); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - } + } - @Test - public void testSendBatchWithResponseProtAaf() throws Exception { + @Test + public void testSendBatchWithResponsePrAuthKey() throws Exception { - setUp(null); + setUp(null); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - } + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - @Test - public void testSendBatchWithResponseProtNoAuth() throws Exception { + } - setUp(null); + @Test + public void testSendBatchWithResponsePrAaf() throws Exception { - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + setUp(null); - final List<message> stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - @Test - public void testSendBatchWithResponsecontypeText() throws Exception { + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - setUp("text/plain"); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + @Test + public void testSendBatchWithResponsePrNoauth() throws Exception { - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", "payload"); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + setUp(null); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - @Test - public void testSendBatchWithResponsecontypeCambria() throws Exception { + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - setUp("application/cambria-zip"); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + @Test + public void createPublisherResponse() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", "payload"); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + MRPublisherResponse response = pub.createMRPublisherResponse("{\"message\": \"published the message\", \"status\": \"200\"}", new MRPublisherResponse()); + assertEquals("200", response.getResponseCode()); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + } - } + @Test + public void createPublisherResponseSucc() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - @Test - public void testSendBatchWithResponsePrAuthKey() throws Exception { + MRPublisherResponse response = pub.createMRPublisherResponse("{\"fakemessage\": \"published the message\", \"fakestatus\": \"200\"}", new MRPublisherResponse()); + assertEquals("200", response.getResponseCode()); - setUp(null); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); + @Test + public void createPublisherResponseError() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void testSendBatchWithResponsePrAaf() throws Exception { + MRPublisherResponse response = pub.createMRPublisherResponse("", new MRPublisherResponse()); + assertEquals("400", response.getResponseCode()); - setUp(null); - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void testSendBatchWithResponsePrNoauth() throws Exception { - - setUp(null); - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void createPublisherResponse() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("{\"message\": \"published the message\", \"status\": \"200\"}", new MRPublisherResponse()); - assertEquals("200", response.getResponseCode()); - - } - - @Test - public void createPublisherResponseSucc() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("{\"fakemessage\": \"published the message\", \"fakestatus\": \"200\"}", new MRPublisherResponse()); - assertEquals("200", response.getResponseCode()); - - } - - @Test - public void createPublisherResponseError() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("", new MRPublisherResponse()); - assertEquals("400", response.getResponseCode()); - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java index 362da00..0302edd 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.client.response; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) +@SuiteClasses({MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java index 0676fd7..2a89dae 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,70 +22,71 @@ package org.onap.dmaap.mr.client.response; -import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRConsumerResponseTest { - private MRConsumerResponse test = null; + private MRConsumerResponse test = null; - @Before - public void setUp() throws Exception { - test = new MRConsumerResponse(); + @Before + public void setUp() throws Exception { + test = new MRConsumerResponse(); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetResponseCode() { + @Test + public void testGetResponseCode() { - test.getResponseCode(); - assertTrue(true); + test.getResponseCode(); + assertTrue(true); - } + } - @Test - public void testSetResponseCode() { + @Test + public void testSetResponseCode() { - test.setResponseCode("200"); - assertTrue(true); + test.setResponseCode("200"); + assertTrue(true); - } + } - @Test - public void testGetResponseMessage() { + @Test + public void testGetResponseMessage() { - test.getResponseMessage(); - assertTrue(true); + test.getResponseMessage(); + assertTrue(true); - } + } - @Test - public void testSetResponseMessage() { + @Test + public void testSetResponseMessage() { - test.setResponseMessage("responseMessage"); - assertTrue(true); + test.setResponseMessage("responseMessage"); + assertTrue(true); - } + } - @Test - public void testGetActualMessages() { + @Test + public void testGetActualMessages() { - test.getActualMessages(); - assertTrue(true); + test.getActualMessages(); + assertTrue(true); - } + } - @Test - public void testSetActualMessages() { + @Test + public void testSetActualMessages() { - test.setActualMessages(null); - assertTrue(true); + test.setActualMessages(null); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java index 19c829a..07b4ba3 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,80 +22,81 @@ package org.onap.dmaap.mr.client.response; -import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRPublisherResponseTest { - private MRPublisherResponse response = null; + private MRPublisherResponse response = null; + + @Before + public void setUp() throws Exception { + response = new MRPublisherResponse(); + + } + + @After + public void tearDown() throws Exception { + + } - @Before - public void setUp() throws Exception { - response = new MRPublisherResponse(); + @Test + public void testGetResponseCode() { - } + response.getResponseCode(); + assertTrue(true); - @After - public void tearDown() throws Exception { + } - } + @Test + public void testSetResponseCode() { - @Test - public void testGetResponseCode() { + response.setResponseCode("200"); + assertTrue(true); - response.getResponseCode(); - assertTrue(true); + } - } - - @Test - public void testSetResponseCode() { + @Test + public void testGetResponseMessage() { - response.setResponseCode("200"); - assertTrue(true); + response.getResponseMessage(); + assertTrue(true); - } - - @Test - public void testGetResponseMessage() { + } - response.getResponseMessage(); - assertTrue(true); + @Test + public void testSetResponseMessage() { - } + response.setResponseMessage("responseMessage"); + assertTrue(true); - @Test - public void testSetResponseMessage() { + } - response.setResponseMessage("responseMessage"); - assertTrue(true); + @Test + public void testGetPendingMsgs() { - } + response.getPendingMsgs(); + assertTrue(true); - @Test - public void testGetPendingMsgs() { + } - response.getPendingMsgs(); - assertTrue(true); + @Test + public void testSetPendingMsgs() { - } + response.setPendingMsgs(5); + assertTrue(true); - @Test - public void testSetPendingMsgs() { + } - response.setPendingMsgs(5); - assertTrue(true); + @Test + public void testToString() { - } - - @Test - public void testToString() { + response.toString(); + assertTrue(true); - response.toString(); - assertTrue(true); + } - } - } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java index a5f43d4..c301551 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java deleted file mode 100644 index 5fa72dd..0000000 --- a/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.mr.dme.client; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class DefaultLoggingFailoverFaultHandlerTest { - private DefaultLoggingFailoverFaultHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new DefaultLoggingFailoverFaultHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleEndpointFailover() { - -// handler.handleEndpointFailover(null); - assertTrue(true); - - } - /* - @Test - public void testHandleRouteOfferFailover() { - - handler.handleRouteOfferFailover(null); - assertTrue(true); - - } -*/ -} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java index c3a0bb1..0cc824d 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,60 +22,58 @@ package org.onap.dmaap.mr.dme.client; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; public class HeaderReplyHandlerTest { - private HeaderReplyHandler handler = null; + private HeaderReplyHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new HeaderReplyHandler(); + + } + + @After + public void tearDown() throws Exception { + + } - @Before - public void setUp() throws Exception { - handler = new HeaderReplyHandler(); + @Test + public void testHandleFault() { - } + handler.handleFault(null); + assertTrue(true); - @After - public void tearDown() throws Exception { + } - } + @Test + public void testHandleEndpointFault() { - @Test - public void testHandleFault() { + handler.handleEndpointFault(null); + assertTrue(true); - handler.handleFault(null); - assertTrue(true); + } - } - - @Test - public void testHandleEndpointFault() { + @Test + public void testHandleReply() { - handler.handleEndpointFault(null); - assertTrue(true); + Map<String, String> responseHeaders = new HashMap<String, String>(); + responseHeaders.put("transactionId", "1234"); - } - - @Test - public void testHandleReply() { - - Map <String, String>responseHeaders = new HashMap<String, String>(); - responseHeaders.put("transactionId", "1234"); + DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", + 200, new HashMap<String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); + handler.handleReply(responseData); + assertTrue(true); - DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext ("service", - 200, new HashMap <String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); - handler.handleReply(responseData); - assertTrue(true); + } - } - - } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java index e1f8431..cc13578 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.dme.client; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,18 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ DefaultLoggingFailoverFaultHandlerTest.class, HeaderReplyHandlerTest.class,PreferredRouteReplyHandlerTest.class, - PreferredRouteRequestHandlerTest.class,SimpleExamplePublisherTest.class }) - +@SuiteClasses({HeaderReplyHandlerTest.class, PreferredRouteReplyHandlerTest.class, + PreferredRouteRequestHandlerTest.class, SimpleExamplePublisherTest.class}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java index acfea5a..fb3b8d0 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,70 +22,64 @@ package org.onap.dmaap.mr.dme.client; -import java.util.HashMap; -import java.util.Map; - +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import java.util.HashMap; +import java.util.Map; + import static org.junit.Assert.assertNotNull; public class PreferredRouteReplyHandlerTest { - private PreferredRouteReplyHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new PreferredRouteReplyHandler(); - - } - - @After - public void tearDown() throws Exception { + private PreferredRouteReplyHandler handler = null; - } + @Before + public void setUp() throws Exception { + handler = new PreferredRouteReplyHandler(); - @Test - public void testHandleReply() { - - Map <String, String> responseHeaders = new HashMap <String, String>(); - responseHeaders.put("transactionId", "1234"); + } - DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext ("service", - 200, new HashMap<String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); + @After + public void tearDown() throws Exception { - handler.handleReply(responseData); - assert(true); - assertNotNull(responseHeaders); + } - } -/* - @Test - public void testHandleFault() { - - handler.handleFault(null); - assertTrue(true); + @Test + public void testHandleReply() { - } - - @Test - public void testHandleEndpointFault() { + Map<String, String> responseHeaders = new HashMap<String, String>(); + responseHeaders.put("transactionId", "1234"); - handler.handleEndpointFault(null); - assertTrue(true); + DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", + 200, new HashMap<String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); - } - - @Test - public void testRouteWriter() { + handler.handleReply(responseData); + assert (true); + assertNotNull(responseHeaders); - handler.routeWriter("routeKey", "routeValue"); - assertTrue(true); + } +/* + @Test + public void testHandleFault() { + handler.handleFault(null); + assertTrue(true); + } + + @Test + public void testHandleEndpointFault() { + handler.handleEndpointFault(null); + assertTrue(true); + } + + @Test + public void testRouteWriter() { + handler.routeWriter("routeKey", "routeValue"); + assertTrue(true); + } - } - */ - + } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java index 167f3ff..01e6c69 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,39 +26,43 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class PreferredRouteRequestHandlerTest { - private PreferredRouteRequestHandler handler = null; +import static org.junit.Assert.assertTrue; - @Before - public void setUp() throws Exception { - handler = new PreferredRouteRequestHandler(); +public class PreferredRouteRequestHandlerTest { + private PreferredRouteRequestHandler handler = null; - } + @Before + public void setUp() throws Exception { + handler = new PreferredRouteRequestHandler(); - @After - public void tearDown() throws Exception { + } - } + @After + public void tearDown() throws Exception { - @Test - public void testHandleRequest() { + } - /* handler.handleRequest(null); - assertTrue(true);*/ + @Test + public void testHandleRequest() { - } + assertTrue(true); + /* + handler.handleRequest(null); + assertTrue(true);*/ - @Test - public void testReadRoute() { + } -// try { -// handler.readRoute("routeKey"); -// } catch (NullPointerException e) { -// assertTrue(true); -// } + @Test + public void testReadRoute() { + assertTrue(true); +// try { +// handler.readRoute("routeKey"); +// } catch (NullPointerException e) { +// assertTrue(true); +// } // -// assertTrue(true); +// assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java new file mode 100644 index 0000000..ab49cb3 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MultivaluedMap; +import java.util.List; +import java.util.Map; + +public class SimpleExampleConsumer { + + private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + private SimpleExampleConsumer() { + } + + public static void main(String[] args) { + + long count = 0; + long nextReport = 5000; + String key; + + final long startMs = System.currentTimeMillis(); + + try { + + final MRConsumer cc = MRClientFactory.createConsumer("D:\\SG\\consumer.properties"); + while (true) { + for (String msg : cc.fetch()) { + logger.debug("Message Received: " + msg); + } + // Header for DME2 Call. + MultivaluedMap<String, Object> headersMap = MRClientFactory.getHTTPHeadersMap(); + for (Map.Entry<String, List<Object>> entry : headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + headersMap.get(key)); + } + // Header for HTTP Call. + + Map<String, String> dme2headersMap = MRClientFactory.DME2HeadersMap; + for (Map.Entry<String, String> entry : dme2headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + dme2headersMap.get(key)); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + } + } + } catch (Exception x) { + logger.error("Exception in SimpleExampleConsumer", x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java new file mode 100644 index 0000000..6a67774 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; + +import javax.ws.rs.core.MultivaluedMap; +import java.io.IOException; +import java.util.Map; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisher { + static String content = null; + static String messageSize = null; + static String transport = null; + static String messageCount = null; + + public void publishMessage(String producerFilePath) throws IOException, InterruptedException { + + // create our publisher + // publish some messages + + StringBuilder sb = new StringBuilder(); + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); + + if (content.equalsIgnoreCase("text/plain")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("T"); + } + + pub.send(sb.toString()); + } + } else if (content.equalsIgnoreCase("application/cambria")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("C"); + } + pub.send("Key", sb.toString()); + } + } else if (content.equalsIgnoreCase("application/json")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + + final JSONObject msg12 = new JSONObject(); + msg12.put("Name", "DMaaP Reference Client to Test jason Message"); + + pub.send(msg12.toString()); + + } + } + + // close the publisher to make sure everything's sent before exiting. + // The batching + // publisher interface allows the app to get the set of unsent messages. + // It could + // write them to disk, for example, to try to send them later. + /* final List<message> stuck = pub.close(20, TimeUnit.SECONDS); + if (stuck.size() > 0) { + System.err.println(stuck.size() + " messages unsent"); + } else { + System.out.println("Clean exit; all messages sent."); + }*/ + + if (transport.equalsIgnoreCase("HTTP")) { + MultivaluedMap<String, Object> headersMap = MRClientFactory.getHTTPHeadersMap(); + for (String key : headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + headersMap.get(key)); + } + } else { + Map<String, String> dme2headersMap = MRClientFactory.DME2HeadersMap; + for (String key : dme2headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + dme2headersMap.get(key)); + } + } + + } + + public static void main(String[] args) throws InterruptedException, Exception { + + String producerFilePath = args[0]; + content = args[1]; + messageSize = args[2]; + transport = args[3]; + messageCount = args[4]; + + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + publisher.publishMessage("D:\\SG\\producer.properties"); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java index 477e92c..f787d88 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +22,38 @@ package org.onap.dmaap.mr.dme.client; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; + private SimpleExamplePublisher pub = null; - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testPublishMessage() { + @Test + public void testPublishMessage() { - try { - pub.publishMessage("/producer"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + pub.publishMessage("/producer"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java index 59fc7f0..8b31b77 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java new file mode 100644 index 0000000..503af01 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * A simple publisher that reads from std in, sending each line as a message. + * + * @author author + */ +public class ConsolePublisher { + + private static final Logger logger = LoggerFactory.getLogger(ConsolePublisher.class); + + private ConsolePublisher() { + } + + public static void main(String[] args) throws IOException //throws IOException, InterruptedException + { + // read the hosts(s) from the command line + final String hosts = args.length > 0 ? args[0] : "mr1.onap.com,mr2.onap.com,mr3.onap.com"; + + // read the topic name from the command line + final String topic = args.length > 1 ? args[1] : "TEST-TOPIC"; + + // read the topic name from the command line + final String partition = args.length > 2 ? args[2] : UUID.randomUUID().toString(); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final long maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(hosts, topic, maxBatchSize, maxAgeMs, withGzip); + + final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); + try { + String line = null; + while ((line = cin.readLine()) != null) { + pub.send(partition, line); + } + } finally { + List<Message> leftovers = null; + try { + leftovers = pub.close(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + logger.error("Send on close interrupted."); + Thread.currentThread().interrupt(); + } + for (Message m : leftovers) { + logger.error("Unsent message: " + m.fMsg); + } + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java index be0574a..41039d8 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class ConsolePublisherTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - ConsolePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + ConsolePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java index a0c81a8..8152972 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.test.clients; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,19 +30,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, - SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, - SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) +@SuiteClasses({SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, + SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, + SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java index 573be98..1dd8381 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,38 +22,39 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.mr.client.ProtocolType; + +import static org.junit.Assert.assertTrue; public class ProtocolTypeConstantsTest { - private ProtocolTypeConstants constants = null; + private ProtocolType constants = null; + + @Before + public void setUp() throws Exception { + // constants = new ProtocolTypeConstants(); - @Before - public void setUp() throws Exception { - // constants = new ProtocolTypeConstants(); + } - } + @After + public void tearDown() throws Exception { - @After - public void tearDown() throws Exception { + } - } + @Test + public void testGetValue() { - @Test - public void testGetValue() { + try { + constants.getValue(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - try { - constants.getValue(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + } - } - } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java new file mode 100644 index 0000000..215ddda --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; + +public class SampleConsumer { + private SampleConsumer() { + } + + public static void main(String[] args) { + final Logger logger = LoggerFactory.getLogger(SampleConsumer.class); + + + logger.info("Sample Consumer Class executing"); + final String topic = "org.onap.dmaap.mr.testingTopic"; + final String url = (args.length > 1 ? args[1] : "localhost:8181"); + final String group = (args.length > 2 ? args[2] : "grp"); + + final String id = (args.length > 3 ? args[3] : "1"); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis(); + + final LinkedList<String> urlList = new LinkedList<>(); + for (String u : url.split(",")) { + urlList.add(u); + } + + final MRConsumer cc = MRClientFactory.createConsumer(urlList, topic, group, id, 10 * 1000, 1000, null, "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88"); + try { + while (true) { + for (String msg : cc.fetch()) { + logger.info("" + (++count) + ": " + msg); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + logger.info("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + logger.info("" + (++count) + ": consumed message"); + } + } catch (Exception x) { + logger.error(x.getClass().getName() + ": " + x.getMessage()); + throw new IllegalArgumentException(x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java index 8d359f4..1c95f1d 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,34 +22,34 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SampleConsumerTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SampleConsumer.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); + try { + SampleConsumer.main(new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java new file mode 100644 index 0000000..0c80194 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class SamplePublisher { + public static void main(String[] args) throws IOException, InterruptedException { + final Logger logger = LoggerFactory.getLogger(SampleConsumer.class); + // read the hosts(s) from the command line + final String hosts = (args.length > 0 ? args[0] : "localhost:8181"); + + // read the topic name from the command line + + final String topic = (args.length > 1 ? args[1] : "org.onap.dmaap.mr.testingTopic"); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final int maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + + final MRBatchingPublisher pub = new PublisherBuilder(). + usingHosts(hosts). + onTopic(topic).limitBatch(maxBatchSize, maxAgeMs). + authenticatedBy("CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88"). + build(); + // publish some messages + final JSONObject msg1 = new JSONObject(); + msg1.put("name", "tttttttttttttttt"); + msg1.put("greeting", "ooooooooooooooooo"); + pub.send("MyPartitionKey", msg1.toString()); + + final JSONObject msg2 = new JSONObject(); + msg2.put("now", System.currentTimeMillis()); + pub.send("MyOtherPartitionKey", msg2.toString()); + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List<Message> stuck = pub.close(20, TimeUnit.SECONDS); + if (!stuck.isEmpty()) { + logger.warn(stuck.size() + " messages unsent"); + } else { + logger.info("Clean exit; all messages sent."); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java index 33f80e5..7c74a05 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SamplePublisherTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SamplePublisher.main( new String[0]); - } catch (Exception e) { - // TODO Auto-generated catch block - assertTrue(true); - } - assertTrue(true); + try { + SamplePublisher.main(new String[0]); + } catch (Exception e) { + // TODO Auto-generated catch block + assertTrue(true); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java new file mode 100644 index 0000000..feb825d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +public class SimpleExampleConsumer { + + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) { + final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis(); + + try { + String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer("/src/main/resources/dme2/consumer.properties"); + int i = 0; + while (i < 10) { + Thread.sleep(2); + i++; + for (String msg : cc.fetch()) { + + System.out.println(msg); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } catch (Exception x) { + System.err.println(x.getClass().getName() + ": " + x.getMessage()); + logger.error("exception: ", x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java index 1ccc839..532e040 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExampleConsumerTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SimpleExampleConsumer.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + SimpleExampleConsumer.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java new file mode 100644 index 0000000..6374ab5 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +public class SimpleExampleConsumerWithReturnResponse { + + private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumerWithReturnResponse.class); + + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) { + + long count = 0; + long nextReport = 5000; + // remove while true and limite execution time in seconds + int timeMax = 86400; // one day + long endDate = System.currentTimeMillis() + timeMax * 1000; + + final long startMs = System.currentTimeMillis(); + + try { + String routeFilePath = "src/main/resources/dme2/preferredRoute.txt"; + + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer("src/main/resources/dme2/consumer.properties"); + while (System.currentTimeMillis() < endDate) { + MRConsumerResponse mrConsumerResponse = cc.fetchWithReturnConsumerResponse(); + System.out.println("mrConsumerResponse code :" + mrConsumerResponse.getResponseCode()); + + System.out.println("mrConsumerResponse Message :" + mrConsumerResponse.getResponseMessage()); + + System.out.println("mrConsumerResponse ActualMessage :" + mrConsumerResponse.getActualMessages()); + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + } + } catch (Exception x) { + System.err.println(x.getClass().getName() + ": " + x.getMessage()); + logger.error("exception: ", x); + } + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java index d814125..0dc04ea 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,34 +22,34 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExampleConsumerWithReturnResponseTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SimpleExampleConsumerWithReturnResponse.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block e.printStackTrace(); - } - assertTrue(true); + try { + SimpleExampleConsumerWithReturnResponse.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java new file mode 100644 index 0000000..a30d45d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisher { + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public void publishMessage(String producerFilePath) throws IOException, InterruptedException, Exception { + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); + // publish some messages + final JSONObject msg1 = new JSONObject(); + msg1.put("Name", "Sprint"); + + pub.send("First cambria messge"); + pub.send("MyPartitionKey", msg1.toString()); + + final JSONObject msg2 = new JSONObject(); + + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List<Message> stuck = pub.close(20, TimeUnit.SECONDS); + if (stuck.isEmpty()) { + System.err.println(stuck.size() + " messages unsent"); + } else { + System.out.println("Clean exit; all messages sent."); + } + } + + public static void main(String[] args) throws InterruptedException, Exception { + + String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + publisher.publishMessage("/src/main/resources/dme2/producer.properties"); + } + +} + diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java index 43faf5e..5449400 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,61 +22,61 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testPublishMessage() { - try { - pub.publishMessage("/producer"); - } catch (NullPointerException e) { - assertTrue(true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testMain() { - - try { - SimpleExamplePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - + private SimpleExamplePublisher pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testPublishMessage() { + try { + pub.publishMessage("/producer"); + } catch (NullPointerException e) { + assertTrue(true); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testMain() { + + try { + SimpleExamplePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java new file mode 100644 index 0000000..08bc778 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Properties; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisherWithResponse { + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) throws InterruptedException, Exception { + + String routeFilePath = "src/main/resources/dme2/preferredRoute.txt"; + String msgCount = args[0]; + SimpleExamplePublisherWithResponse publisher = new SimpleExamplePublisherWithResponse(); + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + int i = 0; + while (i < Integer.valueOf(msgCount)) { + publisher.publishMessage("src/main/resources/dme2/producer.properties", Integer.valueOf(msgCount)); + i++; + } + } + + public void publishMessage(String producerFilePath, int count) throws IOException, InterruptedException { + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath, true); + // publish some messages + final JSONObject msg1 = new JSONObject(); + + msg1.put("Partition:1", "Message:" + count); + msg1.put("greeting", "Hello .."); + + + pub.send("1", msg1.toString()); + pub.send("1", msg1.toString()); + + MRPublisherResponse res = pub.sendBatchWithResponse(); + + System.out.println("Pub response->" + res.toString()); + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java index 08dec2b..0b6e182 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,48 +22,43 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherWithResponseTest { - - private SimpleExamplePublisherWithResponse pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisherWithResponse(); - } - @After - public void tearDown() throws Exception { + private SimpleExamplePublisherWithResponse pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisherWithResponse(); + } - } + @After + public void tearDown() throws Exception { - @Test - public void testMain() { + } - try { - SimpleExamplePublisherWithResponse.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); + @Test + public void testMain() { - } - - @Test - public void testPublishMessage() { + try { + SimpleExamplePublisherWithResponse.main(new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); - try { - pub.publishMessage("/producer", 100); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + } - } + @Test(expected = FileNotFoundException.class) + public void testPublishMessage() throws IOException, InterruptedException { + pub.publishMessage("/producer", 100); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java index 6db09f8..0b4a74b 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java index 3c3b4c8..d244f34 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.test.support; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) +@SuiteClasses({MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java new file mode 100644 index 0000000..beaf9e9 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.support; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; +import org.slf4j.Logger; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * A helper for unit testing systems that use a MRPublisher. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + */ +public class MRBatchingPublisherMock implements MRBatchingPublisher { + public class Entry { + public Entry(String partition, String msg) { + fPartition = partition; + fMessage = msg; + } + + @Override + public String toString() { + return fMessage; + } + + public final String fPartition; + public final String fMessage; + } + + public MRBatchingPublisherMock() { + fCaptures = new LinkedList<>(); + } + + public interface Listener { + void onMessage(Entry e); + } + + public void addListener(Listener listener) { + fListeners.add(listener); + } + + public List<Entry> getCaptures() { + return getCaptures(new MessageFilter() { + @Override + public boolean match(String msg) { + return true; + } + }); + } + + public interface MessageFilter { + boolean match(String msg); + } + + public List<Entry> getCaptures(MessageFilter filter) { + final LinkedList<Entry> result = new LinkedList<>(); + for (Entry capture : fCaptures) { + if (filter.match(capture.fMessage)) { + result.add(capture); + } + } + return result; + } + + public int received() { + return fCaptures.size(); + } + + public void reset() { + fCaptures.clear(); + } + + @Override + public int send(String partition, String msg) { + final Entry e = new Entry(partition, msg); + + fCaptures.add(e); + for (Listener l : fListeners) { + l.onMessage(e); + } + return 1; + } + + @Override + public int send(Message msg) { + return send(msg.fPartition, msg.fMsg); + } + + @Override + public int send(String msg) { + return 1; + + } + + @Override + public int send(Collection<Message> msgs) { + int sum = 0; + for (Message m : msgs) { + sum += send(m); + } + return sum; + } + + @Override + public int getPendingMessageCount() { + return 0; + } + + @Override + public List<Message> close(long timeout, TimeUnit timeoutUnits) { + return new LinkedList<>(); + } + + @Override + public void close() { + } + + @Override + public void setApiCredentials(String apiKey, String apiSecret) { + } + + @Override + public void clearApiCredentials() { + } + + @Override + public void logTo(Logger log) { + } + + private final LinkedList<Entry> fCaptures; + private LinkedList<Listener> fListeners = new LinkedList<>(); + + @Override + public MRPublisherResponse sendBatchWithResponse() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java index af76c52..1de5bcb 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,166 +22,165 @@ package org.onap.dmaap.mr.test.support; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.mr.client.MRPublisher.Message; -import org.onap.dmaap.mr.client.MRPublisher.message; +import java.util.ArrayList; + +import static org.junit.Assert.assertTrue; public class MRBatchingPublisherMockTest { - private MRBatchingPublisherMock pub = null; + private MRBatchingPublisherMock pub = null; + + private MRBatchingPublisherMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + pub = new MRBatchingPublisherMock(); + entry = pub.new Entry("partition", "msg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testToString() { + + entry.toString(); + assertTrue(true); + + } + + @Test + public void testAddListener() { + + pub.addListener(null); + assertTrue(true); + + } + + @Test + public void testGetCaptures() { + + pub.getCaptures(); + assertTrue(true); + + } - private MRBatchingPublisherMock.Entry entry = null; + @Test + public void testGetCaptures2() { - @Before - public void setUp() throws Exception { - pub = new MRBatchingPublisherMock(); - entry = pub.new Entry("partition", "msg"); + pub.getCaptures(null); + assertTrue(true); - } + } - @After - public void tearDown() throws Exception { + @Test + public void testReceived() { - } + pub.received(); + assertTrue(true); - @Test - public void testToString() { + } - entry.toString(); - assertTrue(true); + @Test + public void testResend() { - } + pub.reset(); + assertTrue(true); - @Test - public void testAddListener() { + } - pub.addListener(null); - assertTrue(true); + @Test + public void testSend() { - } + pub.send("partition", "msg"); + assertTrue(true); - @Test - public void testGetCaptures() { + } - pub.getCaptures(); - assertTrue(true); + @Test + public void testSend2() { - } + pub.send("msg"); + assertTrue(true); - @Test - public void testGetCaptures2() { + } - pub.getCaptures(null); - assertTrue(true); + @Test + public void testSend3() { + //sending message m obj + pub.send(new ArrayList<Message>()); + assertTrue(true); - } + } - @Test - public void testReceived() { + @Test + public void testSend4() { + //sending collection of message m objects + pub.send(new Message("partition", "msg")); + assertTrue(true); - pub.received(); - assertTrue(true); + } - } - - @Test - public void testResend() { + @Test + public void testSendBatchWithResponse() { - pub.reset(); - assertTrue(true); + pub.sendBatchWithResponse(); + assertTrue(true); - } - - @Test - public void testSend() { + } - pub.send("partition", "msg"); - assertTrue(true); + @Test + public void testLogTo() { - } - - @Test - public void testSend2() { + pub.logTo(null); + assertTrue(true); - pub.send("msg"); - assertTrue(true); + } - } - - @Test - public void testSend3() { - //sending message m obj - pub.send(new ArrayList<message>()); - assertTrue(true); + @Test + public void testClearApiCredentials() { - } - - @Test - public void testSend4() { - //sending collection of message m objects - pub.send(new message("partition", "msg")); - assertTrue(true); + pub.clearApiCredentials(); + assertTrue(true); - } - - @Test - public void testSendBatchWithResponse() { + } - pub.sendBatchWithResponse(); - assertTrue(true); + @Test + public void testSetApiCredentials() { - } - - @Test - public void testLogTo() { + pub.setApiCredentials("apikey", "apisecret"); + assertTrue(true); - pub.logTo(null); - assertTrue(true); + } - } - - @Test - public void testClearApiCredentials() { + @Test + public void testClose() { - pub.clearApiCredentials(); - assertTrue(true); + pub.close(); + assertTrue(true); - } - - @Test - public void testSetApiCredentials() { + } - pub.setApiCredentials("apikey", "apisecret"); - assertTrue(true); + @Test + public void testClose2() { - } - - @Test - public void testClose() { + pub.close(100, null); + assertTrue(true); - pub.close(); - assertTrue(true); + } - } - - @Test - public void testClose2() { + @Test + public void testGetPendingMessageCount() { - pub.close(100, null); - assertTrue(true); + pub.getPendingMessageCount(); + assertTrue(true); - } - - @Test - public void testGetPendingMessageCount() { - - pub.getPendingMessageCount(); - assertTrue(true); - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java new file mode 100644 index 0000000..55cd245 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.support; + +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.slf4j.Logger; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +/** + * A helper for unit testing systems that use a MRConsumer. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + */ +public class MRConsumerMock implements MRConsumer { + public class Entry { + public Entry(long waitMs, int statusCode, List<String> msgs) { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = null; + fMsgs = new LinkedList<>(msgs); + } + + public Entry(long waitMs, int statusCode, String statusMsg) { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = statusMsg; + fMsgs = null; + } + + public LinkedList<String> run() throws IOException { + try { + Thread.sleep(fWaitMs); + if (fStatusCode >= 200 && fStatusCode <= 299) { + return fMsgs; + } + throw new IOException("" + fStatusCode + " " + fStatusMsg); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(e); + } + } + + private final long fWaitMs; + private final int fStatusCode; + private final String fStatusMsg; + private final LinkedList<String> fMsgs; + } + + public MRConsumerMock() { + fReplies = new LinkedList<>(); + } + + @Override + public void close() { + } + + @Override + public void setApiCredentials(String apiKey, String apiSecret) { + } + + @Override + public void clearApiCredentials() { + } + + public synchronized void add(Entry e) { + fReplies.add(e); + } + + public void addImmediateMsg(String msg) { + addDelayedMsg(0, msg); + } + + public void addDelayedMsg(long delay, String msg) { + final LinkedList<String> list = new LinkedList<>(); + list.add(msg); + add(new Entry(delay, 200, list)); + } + + public void addImmediateMsgGroup(List<String> msgs) { + addDelayedMsgGroup(0, msgs); + } + + public void addDelayedMsgGroup(long delay, List<String> msgs) { + final LinkedList<String> list = new LinkedList<>(msgs); + add(new Entry(delay, 200, list)); + } + + public void addImmediateError(int statusCode, String statusText) { + add(new Entry(0, statusCode, statusText)); + } + + @Override + public Iterable<String> fetch() throws IOException { + return fetch(-1, -1); + } + + @Override + public Iterable<String> fetch(int timeoutMs, int limit) throws IOException { + return fReplies.size() > 0 ? fReplies.removeFirst().run() : new LinkedList<String>(); + } + + @Override + public void logTo(Logger log) { + } + + private final LinkedList<Entry> fReplies; + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse() { + // TODO Auto-generated method stub + return null; + } + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, + int limit) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java index b3c4174..de5420a 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,150 +22,150 @@ package org.onap.dmaap.mr.test.support; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class MRConsumerMockTest { - private MRConsumerMock cons = null; - private MRConsumerMock.Entry entry = null; - - @Before - public void setUp() throws Exception { - cons = new MRConsumerMock(); - entry = cons.new Entry(100, 200, "statusMsg"); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testClose() { - - cons.close(); - assertTrue(true); - - } - - @Test - public void testRun() { - try { - entry.run(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testSetApiCredentials() { - cons.setApiCredentials("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testClearApiCredentials() { - cons.clearApiCredentials(); - assertTrue(true); - - } - - @Test - public void testAdd() { - cons.add(entry); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsg() { - cons.addImmediateMsg("ImmediateMsg"); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsg() { - cons.addDelayedMsg(100, "msg"); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsgGroup() { - cons.addImmediateMsgGroup(new ArrayList<String>()); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsgGroup() { - cons.addDelayedMsgGroup(100,new ArrayList<String>()); - assertTrue(true); - - } - - @Test - public void testAddImmediateError() { - cons.addImmediateError(200, "OK"); - assertTrue(true); - - } - - @Test - public void testFetch() { - try { - cons.fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testFetch2() { - try { - cons.fetch(100, 200); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testLogTo() { - cons.logTo(null); - assertTrue(true); - - } - - @Test - public void testFetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(); - assertTrue(true); - - } - - @Test - public void testGetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(100,200); - assertTrue(true); - - } + private MRConsumerMock cons = null; + private MRConsumerMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + cons = new MRConsumerMock(); + entry = cons.new Entry(100, 200, "statusMsg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testClose() { + + cons.close(); + assertTrue(true); + + } + + @Test + public void testRun() { + try { + entry.run(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testSetApiCredentials() { + cons.setApiCredentials("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testClearApiCredentials() { + cons.clearApiCredentials(); + assertTrue(true); + + } + + @Test + public void testAdd() { + cons.add(entry); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsg() { + cons.addImmediateMsg("ImmediateMsg"); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsg() { + cons.addDelayedMsg(100, "msg"); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsgGroup() { + cons.addImmediateMsgGroup(new ArrayList<String>()); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsgGroup() { + cons.addDelayedMsgGroup(100, new ArrayList<String>()); + assertTrue(true); + + } + + @Test + public void testAddImmediateError() { + cons.addImmediateError(200, "OK"); + assertTrue(true); + + } + + @Test + public void testFetch() { + try { + cons.fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testFetch2() { + try { + cons.fetch(100, 200); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testLogTo() { + cons.logTo(null); + assertTrue(true); + + } + + @Test + public void testFetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(); + assertTrue(true); + + } + + @Test + public void testGetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(100, 200); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java index 69f499f..f10ac2b 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java index f86d4f2..cd801c3 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +22,10 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,185 +33,188 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRClient.MRApiException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRIdentityManager; +import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRClient.MRApiException; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRIdentityManager; -import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class }) +@PrepareForTest({MRClientFactory.class}) public class ApiKeyCommandTest { - @InjectMocks - private ApiKeyCommand command; - @Mock - private MRIdentityManager tm; - @Mock - private ApiKey ti; - @Mock - private ApiKey key; - @Mock - private ApiCredential ac; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); - PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(),printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } + @InjectMocks + private ApiKeyCommand command; + @Mock + private MRIdentityManager tm; + @Mock + private ApiKey ti; + @Mock + private ApiKey key; + @Mock + private ApiCredential ac; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); + PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java index e312d9b..4966f30 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,10 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -34,82 +33,84 @@ import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.PrintStream; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class AuthCommandTest { - @InjectMocks - private AuthCommand command = null; - @Mock - private PrintStream printStream; + @InjectMocks + private AuthCommand command = null; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() { + @Test + public void testExecute() { - try { - String[] parts = new String[5]; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + String[] parts = new String[5]; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute1() { + @Test + public void testExecute1() { - try { - String[] parts = { "userName", "password" }; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + String[] parts = {"userName", "password"}; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java index 5d78488..e503e21 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,12 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.Arrays; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -37,72 +34,76 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.FileNotFoundException; +import java.io.PrintStream; +import java.util.Arrays; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class ClusterCommandTest { - @InjectMocks - private ClusterCommand command; - @Mock - private MRCommandContext context; - @Mock - private PrintStream printStream; + @InjectMocks + private ClusterCommand command; + @Mock + private MRCommandContext context; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); - } + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(context); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(context); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() throws FileNotFoundException, CommandNotReadyException { - String[] parts = { "create", "testtopic", "1", "1" }; - command.execute(parts, context, printStream); - assertTrue(true); + @Test + public void testExecute() throws FileNotFoundException, CommandNotReadyException { + String[] parts = {"create", "testtopic", "1", "1"}; + command.execute(parts, context, printStream); + assertTrue(true); - } + } - @Test - public void testExecute1() throws FileNotFoundException, CommandNotReadyException { - String[] parts = {}; - command.execute(parts, context, printStream); - assertTrue(true); + @Test + public void testExecute1() throws FileNotFoundException, CommandNotReadyException { + String[] parts = {}; + command.execute(parts, context, printStream); + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java index 782dbb0..a0642ff 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.tools; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,18 +30,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, - MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) +@SuiteClasses({ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, + MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java index 8e778d4..806f302 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,135 +22,134 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRCommandContextTest { - private MRCommandContext command = null; - private String[] parts = new String[5]; + private MRCommandContext command = null; + private String[] parts = new String[5]; - @Before - public void setUp() throws Exception { - command = new MRCommandContext(); + @Before + public void setUp() throws Exception { + command = new MRCommandContext(); - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testRequestShutdown() { + @Test + public void testRequestShutdown() { - command.requestShutdown(); - assertTrue(true); + command.requestShutdown(); + assertTrue(true); - } + } - @Test - public void testShouldContinue() { + @Test + public void testShouldContinue() { - command.shouldContinue(); - assertTrue(true); + command.shouldContinue(); + assertTrue(true); - } + } - @Test - public void testSetAuth() { + @Test + public void testSetAuth() { - command.setAuth("key", "pwd"); - assertTrue(true); + command.setAuth("key", "pwd"); + assertTrue(true); - } + } - @Test - public void testClearAuth() { + @Test + public void testClearAuth() { - command.clearAuth(); - assertTrue(true); + command.clearAuth(); + assertTrue(true); - } + } - @Test - public void testCheckClusterReady() { + @Test + public void testCheckClusterReady() { - command.checkClusterReady(); - assertTrue(true); + command.checkClusterReady(); + assertTrue(true); - } + } - @Test - public void testGetCluster() { + @Test + public void testGetCluster() { - command.getCluster(); - assertTrue(true); + command.getCluster(); + assertTrue(true); - } + } - @Test - public void testClearCluster() { + @Test + public void testClearCluster() { - command.clearCluster(); - assertTrue(true); + command.clearCluster(); + assertTrue(true); - } + } - @Test - public void testAddClusterHost() { + @Test + public void testAddClusterHost() { - command.addClusterHost("host"); - assertTrue(true); + command.addClusterHost("host"); + assertTrue(true); - } + } - @Test - public void testGetApiKey() { + @Test + public void testGetApiKey() { - command.getApiKey(); - assertTrue(true); + command.getApiKey(); + assertTrue(true); - } + } - @Test - public void testGetApiPwd() { + @Test + public void testGetApiPwd() { - command.getApiPwd(); - assertTrue(true); + command.getApiPwd(); + assertTrue(true); - } + } - @Test - public void testUseTracer() { + @Test + public void testUseTracer() { - command.useTracer(null); - assertTrue(true); + command.useTracer(null); + assertTrue(true); - } + } - @Test - public void testNoTracer() { + @Test + public void testNoTracer() { - command.noTracer(); - assertTrue(true); + command.noTracer(); + assertTrue(true); - } + } - @Test - public void testApplyTracer() { + @Test + public void testApplyTracer() { - command.applyTracer(null); - assertTrue(true); + command.applyTracer(null); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/MRTool.java b/src/test/java/org/onap/dmaap/mr/tools/MRTool.java new file mode 100644 index 0000000..022f2ee --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/MRTool.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.tools; + +import com.att.nsa.cmdtool.CommandLineTool; +import org.onap.dmaap.mr.client.impl.MRClientVersionInfo; + +import java.io.IOException; + +public class MRTool extends CommandLineTool<MRCommandContext> { + protected MRTool() { + super("MR Tool (" + MRClientVersionInfo.getVersion() + ")", "MR> "); + + registerCommand(new ApiKeyCommand()); + registerCommand(new AuthCommand()); + registerCommand(new ClusterCommand()); + registerCommand(new MessageCommand()); + registerCommand(new TopicCommand()); + registerCommand(new TraceCommand()); + } + + public static void main(String[] args) throws IOException { + final MRTool ct = new MRTool(); + final MRCommandContext ccc = new MRCommandContext(); + ct.runFromMain(args, ccc); + } +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java index 933ee48..c6c9af4 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,15 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,181 +30,188 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class, ToolsUtil.class }) +@PrepareForTest({MRClientFactory.class, ToolsUtil.class}) public class MessageCommandTest { - @InjectMocks - private MessageCommand command; - @Mock - private MRConsumer tm; - @Mock - private TopicInfo ti; - @Mock - private MRBatchingPublisher pub; - @Mock - private MRConsumer cc; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.mockStatic(ToolsUtil.class); - PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, - null, null, null)).thenReturn(cc); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List<String[]> parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - assertTrue(true); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error1() { - try { - PowerMockito.doThrow(new Exception()).when(cc).fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List<String[]> parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error2() { - try { - PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); - PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List<String[]> parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - /* - * @Test public void testExecute_error3() { - * - * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, - * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated - * catch block e.printStackTrace(); } catch (InterruptedException e) { // - * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = - * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", - * "testtopic", "2", "3" }; List<String[]> parts = Arrays.asList(parts1, - * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) - * { String[] part = (String[]) iterator.next(); PrintStream printStream = - * new PrintStream(System.out); - * - * MRCommandContext context = new MRCommandContext(); - * PowerMockito.when(ToolsUtil.createBatchPublisher(context, - * "testtopic")).thenReturn(pub); try { command.execute(part, context, - * printStream); } catch (CommandNotReadyException e) { // TODO - * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); - * - * } - */ - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - - } + @InjectMocks + private MessageCommand command; + @Mock + private MRConsumer tm; + @Mock + private TopicInfo ti; + @Mock + private MRBatchingPublisher pub; + @Mock + private MRConsumer cc; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.mockStatic(ToolsUtil.class); + PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, + null, null, null)).thenReturn(cc); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List<String[]> parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + assertTrue(true); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error1() { + try { + PowerMockito.doThrow(new Exception()).when(cc).fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List<String[]> parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error2() { + try { + PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); + PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List<String[]> parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + /* + * @Test public void testExecute_error3() { + * + * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, + * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated + * catch block e.printStackTrace(); } catch (InterruptedException e) { // + * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = + * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", + * "testtopic", "2", "3" }; List<String[]> parts = Arrays.asList(parts1, + * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) + * { String[] part = (String[]) iterator.next(); PrintStream printStream = + * new PrintStream(System.out); + * + * MRCommandContext context = new MRCommandContext(); + * PowerMockito.when(ToolsUtil.createBatchPublisher(context, + * "testtopic")).thenReturn(pub); try { command.execute(part, context, + * printStream); } catch (CommandNotReadyException e) { // TODO + * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); + * + * } + */ + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java index 2fd831b..3e2380f 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java index 080d6d5..115e007 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2018 Nokia * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * 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 @@ -23,12 +25,13 @@ */ package org.onap.dmaap.mr.tools; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import java.util.Arrays; -import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; +import org.onap.dmaap.mr.client.MRBatchingPublisher; + +import java.util.Arrays; +import java.util.List; public class ToolsUtilTest { diff --git a/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java index 4abd1e4..bcb95cd 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +22,9 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,192 +32,196 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRTopicManager; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; -import org.onap.dmaap.mr.client.MRTopicManager; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class }) +@PrepareForTest({MRClientFactory.class}) public class TopicCommandTest { - @InjectMocks - private TopicCommand command; - @Mock - private MRTopicManager tm; - @Mock - private TopicInfo ti; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); - PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "read", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "write", "1" }; - String[] parts3 = { "revoke", "read", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1a", "1a" }; - String[] parts2 = { "grant", "write", "read", "1" }; - List<String[]> parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } + @InjectMocks + private TopicCommand command; + @Mock + private MRTopicManager tm; + @Mock + private TopicInfo ti; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error() { + + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); + PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "read", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "write", "1"}; + String[] parts3 = {"revoke", "read", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List<String[]> parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); + String[] parts1 = {"create", "testtopic", "1a", "1a"}; + String[] parts2 = {"grant", "write", "read", "1"}; + List<String[]> parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java index ab4d670..ae97c1e 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,10 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -34,71 +33,73 @@ import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.PrintStream; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class TraceCommandTest { - @InjectMocks - private TraceCommand command; - private String[] parts = new String[5]; - @Mock - private PrintStream printStream; + @InjectMocks + private TraceCommand command; + private String[] parts = new String[5]; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() { + @Test + public void testExecute() { - try { - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java index baa5440..198f828 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2018 IBM Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,192 +19,244 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.onap.dmaap.mr.client.ProtocolType; import java.util.Properties; -import org.junit.Test; - -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import static org.junit.Assert.*; public class ValidatorUtilTest { @Test public void testValidateForDME2WithNullServiceName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - try{ + props.setProperty("TransportType", ProtocolType.DME2.getValue()); + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("ServiceName is needed", e.getMessage()); } } - + @Test public void testValidateForDME2WithNullTopic() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("topic is needed", e.getMessage()); } - + } - + @Test public void testValidateForDME2WithNullUserName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); props.setProperty("topic", "topic"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("username is needed", e.getMessage()); } - + } - + @Test public void testValidateForDME2WithNullPassword() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("password is needed", e.getMessage()); } - + } - - - - + + @Test public void testValidateForNonDME2WithNullServiceName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - try{ + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("host is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullTopic() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("topic is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullContenttype() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "contenttype is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("contenttype is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullUserName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("contenttype", "contenttype"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("username is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullPassword() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("password is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithAuthKey() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); props.setProperty("password", "password"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authKey is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("authKey is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithOutAuthDate() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); props.setProperty("password", "password"); props.setProperty("authKey", "authKey"); - - - try{ + + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authDate is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("authDate is needed", e.getMessage()); } } - + @Test public void testValidateForNonDME2WithAuthDate() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + + try { + ValidatorUtil.validatePublisher(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("maxBatchSize is needed", e.getMessage()); + } + } + + + @Test + public void testValidateForNonDME2WithMaxAgeMs() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + + try { + ValidatorUtil.validatePublisher(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("maxAgeMs is needed", e.getMessage()); + } + + + } + + @Test + public void testValidateForNonDME2WithMessageSentThreadOccurrence() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); @@ -210,106 +264,95 @@ public class ValidatorUtilTest { props.setProperty("password", "password"); props.setProperty("authKey", "authKey"); props.setProperty("authDate", "authDate"); - - try{ + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxBatchSize is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("MessageSentThreadOccurrence is needed", e.getMessage()); } + } - - - @Test - public void testValidateForNonDME2WithMaxAgeMs() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxAgeMs is needed"); - } - - - + + + @Test + public void testValidateSubscriberWithoutGroup() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try { + ValidatorUtil.validateSubscriber(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("group is needed", e.getMessage()); + } } - - @Test - public void testValidateForNonDME2WithMessageSentThreadOccurance() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "MessageSentThreadOccurance is needed"); - } - + + @Test + public void testValidateSubscriberWithoutCustomer() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + props.setProperty("group", "group"); + + try { + ValidatorUtil.validateSubscriber(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("Consumer (id) is needed", e.getMessage()); } - - - @Test - public void testValidateSubscriberWithoutGroup() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "group is needed"); - } - } - - @Test - public void testValidateSubscriberWithoutCustomer() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - props.setProperty("group", "group"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Consumer (Id) is needed"); - } - } - - - - - + } + + @Test + public void testValidatePublisher() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + props.setProperty("MessageSentThreadOccurrence", "10"); + + try { + ValidatorUtil.validatePublisher(props); + } catch (IllegalArgumentException e) { + fail(); + return; + } + + props.remove("MessageSentThreadOccurrence"); + props.setProperty("MessageSentThreadOccurance", "10"); + try { + ValidatorUtil.validatePublisher(props); + } catch (IllegalArgumentException e) { + fail(); + } + } + + + } |