diff options
author | 2021-04-08 16:40:06 +0100 | |
---|---|---|
committer | 2021-04-21 13:49:22 +0100 | |
commit | 71d3d0925874247de5e657821638b1c08360f571 (patch) | |
tree | 91bcca2c8bd53c3ee54269c3101538cba70fa588 /dmaap-bc/src/test/java | |
parent | 20221353bdb213a1f143a132d819d4e0810e3794 (diff) |
[DMAAP-BC] Consolidate bus controller repos
Migrate BC CSITs to the repo
Fix documentation
Signed-off-by: efiacor <fiachra.corcoran@est.tech>
Change-Id: I874ed61be1b61187e233e9fd0937f6658f0ec0f0
Issue-ID: DMAAP-1544
Diffstat (limited to 'dmaap-bc/src/test/java')
72 files changed, 8789 insertions, 0 deletions
diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafRoleTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafRoleTest.java new file mode 100644 index 0000000..c53d8c6 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafRoleTest.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright 2019 IBM + * ================================================================================ + * 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.dbcapi.aaf; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; + +public class AafRoleTest { + + AafRole aafRole; + + @Before + public void setUp() { + aafRole = new AafRole("testNs", "testRole"); + } + + @Test + public void testAafRole() { + aafRole.setNamespace("namespace"); + aafRole.setRole("role"); + assertEquals("namespace", aafRole.getNamespace()); + assertEquals("role", aafRole.getRole()); + assertEquals("namespace.role", aafRole.getFullyQualifiedRole()); + assertNotNull(aafRole.toJSON()); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceFactoryTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceFactoryTest.java new file mode 100644 index 0000000..45ff2b1 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceFactoryTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.aaf; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; + +@RunWith(MockitoJUnitRunner.class) +public class AafServiceFactoryTest { + + private static final String USE_AAF = "true"; + private static final String AAF_URL = "https://aaf.url/api"; + private static final String ADMIN_USER = "admin_user"; + private static final String TOPIC_MANAGER = "topic_manager"; + private static final String ADMIN_PASS = "admin_pass"; + private static final String MANAGER_PASS = "manager_pass"; + @Mock + private DmaapConfig dmaapConfig; + private AafServiceFactory aafServiceFactory; + + @Before + public void setUp() throws Exception { + aafServiceFactory = new AafServiceFactory(dmaapConfig); + } + + @Test + public void shouldBuildAafServiceForAafAdmin() { + givenDmaapConfig(); + + AafServiceImpl aafService = (AafServiceImpl) aafServiceFactory.initAafService(ServiceType.AAF_Admin); + + assertEquals(ADMIN_USER, aafService.getIdentity()); + assertEquals(AAF_URL, aafService.getAafUrl()); + assertTrue(aafService.isUseAAF()); + } + + @Test + public void shouldBuildAafServiceForTopicManager() { + givenDmaapConfig(); + + AafServiceImpl aafService = (AafServiceImpl) aafServiceFactory.initAafService(ServiceType.AAF_TopicMgr); + + assertEquals(TOPIC_MANAGER, aafService.getIdentity()); + assertEquals(AAF_URL, aafService.getAafUrl()); + assertTrue(aafService.isUseAAF()); + } + + @Test + public void shouldCorrectlyCreateCredentialsForAafAdmin() { + givenDmaapConfig(); + + AafServiceFactory.AafCred cred = aafServiceFactory.getCred(ServiceType.AAF_Admin); + + assertEquals(ADMIN_USER, cred.getIdentity()); + assertEquals(ADMIN_USER + ":" + new AafDecrypt().decrypt(ADMIN_PASS), cred.toString()); + } + + @Test + public void shouldCorrectlyCreateCredentialsForTopicManager() { + givenDmaapConfig(); + + AafServiceFactory.AafCred cred = aafServiceFactory.getCred(ServiceType.AAF_TopicMgr); + + assertEquals(TOPIC_MANAGER, cred.getIdentity()); + assertEquals(TOPIC_MANAGER + ":" + new AafDecrypt().decrypt(MANAGER_PASS), cred.toString()); + } + + private void givenDmaapConfig() { + given(dmaapConfig.getProperty("UseAAF", "false")).willReturn(USE_AAF); + given(dmaapConfig.getProperty("aaf.URL", "https://authentication.domain.netset.com:8100/proxy/")).willReturn(AAF_URL); + given(dmaapConfig.getProperty("aaf.AdminUser", "noMechId@domain.netset.com")).willReturn(ADMIN_USER); + given(dmaapConfig.getProperty("aaf.TopicMgrUser", "noMechId@domain.netset.com")).willReturn(TOPIC_MANAGER); + given(dmaapConfig.getProperty("aaf.AdminPassword", "notSet")).willReturn(ADMIN_PASS); + given(dmaapConfig.getProperty("aaf.TopicMgrPassword", "notSet")).willReturn(MANAGER_PASS); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceImplTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceImplTest.java new file mode 100644 index 0000000..ffd130e --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafServiceImplTest.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.aaf; + +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; + +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@RunWith(JUnitParamsRunner.class) +public class AafServiceImplTest { + + private static final String AAF_URL = "https://aaf.url/"; + private static final String IDENTITY = "dmaap-bc@onap.org"; + private static final boolean USE_AAF = true; + private static final int CREATED = 201; + private static final int OK = 200; + @Mock + private AafConnection aafConnection; + private AafServiceImpl aafService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + given(aafConnection.postAaf(any(AafObject.class), anyString())).willReturn(CREATED); + given(aafConnection.delAaf(any(AafObject.class), anyString())).willReturn(OK); + aafService = new AafServiceImpl(USE_AAF, AAF_URL, IDENTITY, aafConnection); + } + + @Test + public void shouldReturnCorrectIdentity() { + + assertEquals(IDENTITY, aafService.getIdentity()); + } + + @Test + public void shouldAddPermission() { + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.addPerm(perm); + + then(aafConnection).should().postAaf(perm, AAF_URL + "authz/perm"); + assertEquals(CREATED, status); + } + + + @Test + public void shouldAddDmaapGrant() { + DmaapGrant grant = new DmaapGrant(new DmaapPerm("perm", "type", "action"), "roles"); + + int status = aafService.addGrant(grant); + + then(aafConnection).should().postAaf(grant, AAF_URL + "authz/role/perm"); + assertEquals(CREATED, status); + } + + @Test + public void shouldAddUserRole() { + AafUserRole userRole = new AafUserRole("ident", "role"); + + int status = aafService.addUserRole(userRole); + + then(aafConnection).should().postAaf(userRole, AAF_URL + "authz/userRole"); + assertEquals(CREATED, status); + } + + @Test + public void shouldAddRole() { + AafRole role = new AafRole("ns", "role"); + + int status = aafService.addRole(role); + + then(aafConnection).should().postAaf(role, AAF_URL + "authz/role"); + assertEquals(CREATED, status); + } + + @Test + public void shouldAddNamespace() { + AafNamespace ns = new AafNamespace("ns", "ident"); + + int status = aafService.addNamespace(ns); + + then(aafConnection).should().postAaf(ns, AAF_URL + "authz/ns"); + assertEquals(CREATED, status); + } + + @Test + public void shouldNotConnectToAafDuringCreate() { + aafService = new AafServiceImpl(false, AAF_URL, IDENTITY, aafConnection); + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.addPerm(perm); + + verifyZeroInteractions(aafConnection); + assertEquals(CREATED, status); + } + + @Test + @Parameters({"401", "403", "409", "200", "500"}) + public void shouldHandleErrorDuringCreate(int aafServiceReturnedCode) { + given(aafConnection.postAaf(any(AafObject.class), anyString())).willReturn(aafServiceReturnedCode); + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.addPerm(perm); + + assertEquals(aafServiceReturnedCode, status); + } + + @Test + @Parameters({"401", "403", "404", "200", "500"}) + public void shouldHandleErrorDuringDelete(int aafServiceReturnedCode) { + given(aafConnection.delAaf(any(AafObject.class), anyString())).willReturn(aafServiceReturnedCode); + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.delPerm(perm, false); + + assertEquals(aafServiceReturnedCode, status); + } + + @Test + public void shouldDeletePermission() { + DmaapPerm perm = new DmaapPerm("permName", "type", "action"); + + int status = aafService.delPerm(perm, false); + + then(aafConnection).should().delAaf(any(AafEmpty.class), eq(AAF_URL + "authz/perm/permName/type/action")); + assertEquals(OK, status); + } + + @Test + public void shouldDeletePermissionWithForce() { + DmaapPerm perm = new DmaapPerm("permName", "type", "action"); + + int status = aafService.delPerm(perm, true); + + then(aafConnection).should().delAaf(any(AafEmpty.class), eq(AAF_URL + "authz/perm/permName/type/action?force=true")); + assertEquals(OK, status); + } + + @Test + public void shouldDeleteNamespace() { + AafNamespace ns = new AafNamespace("nsName", "ident"); + + int status = aafService.delNamespace(ns, false); + + then(aafConnection).should().delAaf(any(AafEmpty.class), eq(AAF_URL + "authz/ns/nsName")); + assertEquals(OK, status); + } + + @Test + public void shouldDeleteNamespaceWithForce() { + AafNamespace ns = new AafNamespace("nsName", "ident"); + + int status = aafService.delNamespace(ns, true); + + then(aafConnection).should().delAaf(any(AafEmpty.class), eq(AAF_URL + "authz/ns/nsName?force=true")); + assertEquals(OK, status); + } + + @Test + public void shouldReturnExpectedCodeDuringPostWhenUseAffIsSetToFalse() { + aafService = new AafServiceImpl(false, AAF_URL, IDENTITY, aafConnection); + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.addPerm(perm); + + assertEquals(CREATED, status); + } + + @Test + public void shouldReturnExpectedCodeDuringDeleteWhenUseAffIsSetToFalse() { + aafService = new AafServiceImpl(false, AAF_URL, IDENTITY, aafConnection); + DmaapPerm perm = new DmaapPerm("perm", "type", "action"); + + int status = aafService.delPerm(perm, false); + + assertEquals(OK, status); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafUserRoleTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafUserRoleTest.java new file mode 100644 index 0000000..88fff87 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/aaf/AafUserRoleTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 IBM Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 IBM + * =================================================================== + * 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.dbcapi.aaf; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Before; +import org.junit.Test; + +public class AafUserRoleTest { + + AafUserRole aafUserRole; + + @Before + public void setUp() { + aafUserRole = new AafUserRole("xyz", "admin"); + } + + @Test + public void testGetIdentity() { + aafUserRole.setIdentity("xyz"); + assertEquals("xyz", aafUserRole.getIdentity()); + } + + @Test + public void testGetRole() { + aafUserRole.setRole("admin"); + assertEquals("admin", aafUserRole.getRole()); + } + + @Test + public void toJSON() { + AafUserRole role = new AafUserRole("test", "admin"); + assertThat(role.toJSON(), is(" { \"user\": \"test\", \"role\": \"admin\" }")); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AafLurAndFishTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AafLurAndFishTest.java new file mode 100644 index 0000000..af6aba4 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AafLurAndFishTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * 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.dbcapi.authentication; + +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.core.Application; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.Test; + +public class AafLurAndFishTest extends JerseyTest { + + @Before + public void setUp() throws Exception { + System.setProperty("ConfigFile", "src/test/resources/dmaapbc.properties"); + } + + @Override + protected Application configure() { + return new ResourceConfig() + .register( AafLurAndFish.class ); + } + + @Test + public void constructorTest() { + try { + AafLurAndFish p = new AafLurAndFish(); + } catch ( AuthenticationErrorException err ) { + + } + + assertTrue( true ); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AllowAllTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AllowAllTest.java new file mode 100644 index 0000000..9b6ee01 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/AllowAllTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.authentication; + +import org.junit.Test; + +import static org.junit.Assert.fail; + +public class AllowAllTest { + + private AllowAll allowAll = new AllowAll(); + + @Test + public void check_shouldPassValidationForAllPerms() { + try { + allowAll.check(null, null, null); + } catch (Exception e) { + fail("No exception should be thrown"); + } + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPermsTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPermsTest.java new file mode 100644 index 0000000..ea749ce --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPermsTest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * 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.dbcapi.authentication; + +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.core.Application; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; + +import org.onap.dmaap.dbcapi.authentication.ApiPerms; + + +public class ApiPermsTest extends JerseyTest { + + @Override + protected Application configure() { + return new ResourceConfig() + .register( ApiPerms.class ); + } + + @Test + public void bootTest() { + ApiPerms p = new ApiPerms(); + + p.setBootMap(); + + p.setEnvMap(); + + + assertTrue( true ); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPolicyTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPolicyTest.java new file mode 100644 index 0000000..7b9fbb3 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/authentication/ApiPolicyTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.authentication; + +import org.junit.Test; +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; + +import java.util.Properties; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ApiPolicyTest { + + private Properties properties = new Properties(); + private ApiPolicy apiPolicy; + + @Test + public void check_shouldExecuteAuthorizationApi() throws Exception { + properties.put("ApiPermission.Class", "org.onap.dmaap.dbcapi.authentication.ApiPolicyTest$DummyApiAuthorization"); + apiPolicy = new ApiPolicy(properties); + + apiPolicy.check("mechId", "pwd", new DmaapPerm("api.perm", "*", "GET")); + + assertTrue(((DummyApiAuthorization) apiPolicy.getPerm()).isCheckExecuted()); + } + + @Test + public void isPermissionClassSet_shouldReturnTrueForValidApiPermClass() { + properties.put("ApiPermission.Class", "org.onap.dmaap.dbcapi.authentication.ApiPolicyTest$DummyApiAuthorization"); + apiPolicy = new ApiPolicy(properties); + + assertTrue(apiPolicy.isPermissionClassSet()); + } + + @Test + public void isPermissionClassSet_shouldReturnFalseWhenPropertyIsNotSet() { + apiPolicy = new ApiPolicy(properties); + + assertFalse(apiPolicy.isPermissionClassSet()); + } + + @Test + public void isPermissionClassSet_shouldReturnFalseWhenWrongClassIsSet() { + properties.put("ApiPermission.Class", "org.onap.dmaap.dbcapi.authentication.NotExisting"); + apiPolicy = new ApiPolicy(properties); + + assertFalse(apiPolicy.isPermissionClassSet()); + } + + public static class DummyApiAuthorization implements ApiAuthorizationCheckInterface { + + private boolean checkExecuted = false; + + @Override + public void check(String mechid, String pwd, DmaapPerm p) { + checkExecuted = true; + } + + boolean isCheckExecuted() { + return checkExecuted; + } + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java new file mode 100644 index 0000000..4c44e0a --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.client; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Pub; +import org.onap.dmaap.dbcapi.model.DR_Sub; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.service.DcaeLocationService; +import org.onap.dmaap.dbcapi.service.MR_ClusterService; +import org.onap.dmaap.dbcapi.service.TopicService; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class DrProvConnectionTest { + + private static final String fmt = "%24s: %s%n"; + private static DmaapObjectFactory factory = new DmaapObjectFactory(); + + ReflectionHarness rh = new ReflectionHarness(); + + DrProvConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new DrProvConnection(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = factory.genDcaeLocation( "central" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] hl = { "host1", "host2", "host3" }; + ns.makeFeedConnection( ); + ns.makeFeedConnection( "01" ); + ns.makeSubPostConnection( "part0/part1/part2/part3/part4" ); + ns.makeSubPutConnection( "44" ); + ns.makeIngressConnection( "01", "aUser", "10.10.10.10", "aNode" ); + ns.makeEgressConnection( "01", "aNode" ); + ns.makeNodesConnection( "someVar" ); + Feed feed = new Feed( "dgl feed 1" , + "v1.0", + "dgl feed 1 for testing", + "TEST", + "unclassified" + ); + ArrayList<DR_Pub> pubs = new ArrayList<DR_Pub>(); + pubs.add( new DR_Pub( "central-demo" ) ); + feed.setPubs(pubs); + + String resp = ns.doPostFeed( feed, err ); + resp = ns.doPutFeed( feed, err ); + resp = ns.doDeleteFeed( feed, err ); + + int i = ns.doXgressPost( err ); + + DR_Sub sub = factory.genDrSub( "central", feed.getFeedId() ); + assertTrue( sub != null ); + String sr = ns.doPostDr_Sub( sub, err ); + /* + * TODO: + - create a new DR_Sub based on a simulated response + - update using ns.doPutDr_Sub( sub, err ); + */ + } + + @Test + public void test4() { + ApiError err = new ApiError(); + String resp = ns.doGetNodes( err ); + ns.makeNodesConnection( "someVar", "host1|host2" ); + resp = ns.doPutNodes( err ); + try { + InputStream is = new FileInputStream(new File("/src/test/resources/dmaapbc.properties")); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + } + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java new file mode 100644 index 0000000..0614cf9 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.client; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.service.DcaeLocationService; +import org.onap.dmaap.dbcapi.service.MR_ClusterService; +import org.onap.dmaap.dbcapi.service.TopicService; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class MrProvConnectionTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + MrProvConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new MrProvConnection(); + ts = new TopicService(); + mcs = new MR_ClusterService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + + MR_Cluster cluster = new MR_Cluster( locname, "localhost", "http", "3904" ); + mcs.addMr_Cluster( cluster, err ); + ns.makeTopicConnection( cluster ); + Topic topic = new Topic(); + topic.setTopicName( "test5" ); + String resp = ns.doPostTopic( topic, err ); + + try { + InputStream is = new FileInputStream(new File("/src/test/resources/dmaapbc.properties")); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java new file mode 100644 index 0000000..af33ec6 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.client; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.service.DcaeLocationService; +import org.onap.dmaap.dbcapi.service.MR_ClusterService; +import org.onap.dmaap.dbcapi.service.TopicService; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class MrTopicConnectionTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + MrTopicConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new MrTopicConnection( "aUser", "aPwd" ); + ts = new TopicService(); + mcs = new MR_ClusterService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + + MR_Cluster cluster = new MR_Cluster( locname, "localhost", "http", "3904"); + mcs.addMr_Cluster( cluster, err ); + ns.makeTopicConnection( cluster, "org.onap.dmaap.anInterestingTopic", "" ); + String msg = "{ 'key': '1234', 'val': 'hello world' }"; + ApiError e2 = ns.doPostMessage( msg ); + + try { + InputStream is = new FileInputStream(new File("/src/test/resources/dmaapbc.properties")); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java new file mode 100644 index 0000000..f68b9ed --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 IBM + * =================================================================== + * 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.dbcapi.database; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import org.junit.Test; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.model.ReplicationType; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class DBFieldHandlerTest extends BaseLoggingClass { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + + @Test + public void test1() { + // rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", + // "idNotSet@namespaceNotSet:pwdNotSet" ); + } + + @Test + public void test2() { + String v = "Validate"; + // rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + } + + @Test + public void test3() { + try { + DBFieldHandler fh = new DBFieldHandler(String.class, "aString", 1); + } catch (Exception e) { + errorLogger.error("Error", e); + } + } + + @Test + public void test4() { + try { + DBFieldHandler fh = new DBFieldHandler(String.class, "aString", 1, null); + } catch (Exception e) { + errorLogger.error("Error", e); + } + } + + @Test + public void testfesc() { + String sampleString = "@xyz,ww;,"; + String finalString = DBFieldHandler.fesc(sampleString); + assertEquals("@axyz@cww@s@c", finalString); + } + + @Test + public void testfunesc() { + String sampleString = "@axyz@cww@s@c"; + String convertedString = DBFieldHandler.funesc(sampleString); + assertEquals("@xyz,ww;,", convertedString); + } + + @Test + public void testfescWithNull() { + String sampleString1 = DBFieldHandler.fesc(null); + String sampleString2 = DBFieldHandler.funesc(null); + assertNull(null, sampleString1); + assertNull(null, sampleString2); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java new file mode 100644 index 0000000..abd4aee --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.database; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; +import org.onap.dmaap.dbcapi.util.Singleton; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; + +public class DBMapTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + private static Singleton<Dmaap> dmaap; + private static Map<String, DcaeLocation> dcaeLocations; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + try { + dmaap = new DBSingleton<Dmaap>(Dmaap.class, "dmaap"); + Dmaap nd = new Dmaap.DmaapBuilder().createDmaap(); + dmaap.update(nd); + } catch (Exception e ) { + } + try { + dcaeLocations = new DBMap<DcaeLocation>(DcaeLocation.class, "dcae_location", "dcae_location_name"); + } catch (Exception e ) { + } + + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java new file mode 100644 index 0000000..003f250 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java @@ -0,0 +1,67 @@ + +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.database; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DBSingletonTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + + @Test + public void test3() { + + try { + DBSingleton<Dmaap> dmaap = new DBSingleton<Dmaap>(Dmaap.class, "dmaap"); + Dmaap d = new Dmaap.DmaapBuilder().createDmaap(); + dmaap.init( d ); + d = dmaap.get(); + d.setDmaapName( "foo" ); + dmaap.update( d ); + dmaap.remove(); + } catch (Exception e ) { + } + + } + + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java new file mode 100644 index 0000000..99065d3 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.database; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class LoadSchemaTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + LoadSchema ls; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.database.LoadSchema", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.database.LoadSchema", "set", v ); + + } + + @Test + public void test3() { + LoadSchema.loadSchema(); + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java new file mode 100644 index 0000000..978f3ad --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.database; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.sql.*; + +public class TableHandlerTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + DBFieldHandler.SqlOp trth = new TopicReplicationTypeHandler(); + TableHandler.setSpecialCase("topic", "replication_case", trth); + + try { + ConnectionFactory cf = new ConnectionFactory(); + TableHandler th = new TableHandler( cf, TopicReplicationTypeHandler.class, "foo", "bar" ); + DBFieldHandler.SqlOp t = th.getSpecialCase( "foo", "bar" ); + assert( trth == t ); + } catch (Exception e ) { + } + try { + + TableHandler th = new TableHandler( TopicReplicationTypeHandler.class, "foo", "bar" ); + DBFieldHandler.SqlOp t = th.getSpecialCase( "foo", "bar" ); + assert( trth == t ); + } catch (Exception e ) { + } + + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/BrTopicTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/BrTopicTest.java new file mode 100644 index 0000000..11e7c85 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/BrTopicTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright 2019 IBM + * ================================================================================ + * 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.dbcapi.model; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class BrTopicTest { + + BrTopic brTopic; + + @Before + public void setUp() { + brTopic = new BrTopic(); + } + + @Test + public void testGetBrSource() { + brTopic.setBrSource("brSource"); + assertEquals("brSource", brTopic.getBrSource()); + } + + @Test + public void testGetBrTarget() { + brTopic.setBrTarget("brTarget"); + assertEquals("brTarget", brTopic.getBrTarget()); + } + + @Test + public void testGetTopicCount() { + brTopic.setTopicCount(1); + assertEquals(1, brTopic.getTopicCount()); + } + + @Test + public void testGetMmAgentName() { + brTopic.setMmAgentName("Test"); + assertEquals("Test", brTopic.getMmAgentName()); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRNodeTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRNodeTest.java new file mode 100644 index 0000000..ce23656 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRNodeTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +public class DRNodeTest { + String f, d, h, v; + + @Before + public void setUp() throws Exception { + v = "1"; + f = "node01.onap.org"; + h = "zlpdrns01.cloud.onap.org"; + d = "central-onap"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testDRNodeClassDefaultConstructor() { + + DR_Node t = new DR_Node(); + + assertTrue( t.getFqdn() == null ); + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getHostName() == null ); + assertTrue( t.getVersion() == null ); + + } + + @Test + public void testDRNodeClassConstructor() { + + DR_Node t = new DR_Node( f, d, h, v ); + + assertTrue( f.equals( t.getFqdn() )); + assertTrue( d.equals( t.getDcaeLocationName() )); + assertTrue( h.equals( t.getHostName() )); + assertTrue( v.equals( t.getVersion() )); + + } + + @Test + public void testDRNodeClassSetters() { + + DR_Node t = new DR_Node(); + + t.setFqdn( f ); + assertTrue( f.equals( t.getFqdn() )); + t.setDcaeLocationName( d ); + assertTrue( d.equals( t.getDcaeLocationName() )); + t.setHostName( h ); + assertTrue( h.equals( t.getHostName() )); + t.setVersion( v ); + assertTrue( v.equals( t.getVersion() )); + + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRPubTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRPubTest.java new file mode 100644 index 0000000..191f364 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRPubTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +public class DRPubTest { + String d, un, up, f, p; + + @Before + public void setUp() throws Exception { + d = "central-onap"; + un = "user1"; + up = "secretW0rd"; + f = "234"; + p = "678"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testDRPubClassDefaultConstructor() { + + DR_Pub t = new DR_Pub(); + + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getUsername() == null ); + assertTrue( t.getUserpwd() == null ); + assertTrue( t.getFeedId() == null ); + assertTrue( t.getPubId() == null ); + + } + + @Test + public void testDRPubClassConstructor() { + + DR_Pub t = new DR_Pub( d, un, up, f, p ); + + assertTrue( d.equals( t.getDcaeLocationName() )); + assertTrue( un.equals( t.getUsername() )); + assertTrue( up.equals( t.getUserpwd() )); + assertTrue( f.equals( t.getFeedId() )); + assertTrue( p.equals( t.getPubId() )); + } + + @Test + public void testDRPubClassSetters() { + + DR_Pub t = new DR_Pub(); + + t.setDcaeLocationName( d ); + assertTrue( d.equals( t.getDcaeLocationName() )); + t.setUsername( un ); + assertTrue( un.equals( t.getUsername() )); + t.setUserpwd( up ); + assertTrue( up.equals( t.getUserpwd() )); + t.setFeedId( f ); + assertTrue( f.equals( t.getFeedId() )); + t.setPubId( p ); + assertTrue( p.equals( t.getPubId() )); + + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRSubTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRSubTest.java new file mode 100644 index 0000000..95cf9c9 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DRSubTest.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +public class DRSubTest { + String d, un, up, f, du, lu, s, o; + Boolean u100, susp; + + @Before + public void setUp() throws Exception { + d = "central-onap"; + un = "user1"; + up = "secretW0rd"; + f = "22"; + s = "sub123"; + du = "sub.server.onap.org:8443/deliver/here"; + lu = "https://drps.onap.org:8443/sublog/123"; + u100 = true; + susp = false; + o = "joe"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testDRSubClassDefaultConstructor() { + + DR_Sub t = new DR_Sub(); + + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getUsername() == null ); + assertTrue( t.getUserpwd() == null ); + assertTrue( t.getFeedId() == null ); + assertTrue( t.getDeliveryURL() == null ); + assertTrue( t.getLogURL() == null ); + assertTrue( t.getSubId() == null ); + assertTrue( ! t.isUse100() ); + assertTrue( ! t.isSuspended() ); + assertTrue( t.getOwner() == null ); + assertTrue( t.isGuaranteedDelivery() == false ); + assertTrue( t.isGuaranteedSequence() == false ); + assertTrue( t.isPrivilegedSubscriber() == false ); + assertTrue( t.isDecompress() == false ); + } + + @Test + public void testDRSubClassConstructor() { + + DR_Sub t = new DR_Sub( d, un, up, f, du, lu, u100 ); + + assertTrue( d.equals( t.getDcaeLocationName() )); + assertTrue( un.equals( t.getUsername() )); + assertTrue( up.equals( t.getUserpwd() )); + assertTrue( f.equals( t.getFeedId() )); + assertTrue( du.equals( t.getDeliveryURL() ) ); + assertTrue( lu.equals( t.getLogURL() ) ); + assertTrue( t.isUse100() ); + assertTrue( ! t.isSuspended() ); + } + + @Test + public void testDRSubClassSetters() { + + DR_Sub t = new DR_Sub(); + + t.setDcaeLocationName( d ); + assertTrue( d.equals( t.getDcaeLocationName() )); + t.setUsername( un ); + assertTrue( un.equals( t.getUsername() )); + t.setUserpwd( up ); + assertTrue( up.equals( t.getUserpwd() )); + t.setFeedId( f ); + assertTrue( f.equals( t.getFeedId() )); + t.setSubId( s ); + assertTrue( s.equals( t.getSubId() )); + t.setDeliveryURL( du ); + assertTrue( du.equals( t.getDeliveryURL() ) ); + t.setLogURL( lu ); + assertTrue( lu.equals( t.getLogURL() ) ); + boolean v = true; + t.setGuaranteedDelivery( v ); + assertTrue( t.isGuaranteedDelivery() == v ); + t.setGuaranteedSequence(v); + assertTrue( t.isGuaranteedSequence() == v ); + t.setPrivilegedSubscriber(v); + assertTrue( t.isPrivilegedSubscriber() == v ); + t.setDecompress(v); + assertTrue( t.isDecompress() == v ); + } + + @Test + public void testJSONfromONAP() { + + + DR_Sub s = new DR_Sub( d, un, up, f, du, lu, u100 ); + String j = s.toProvJSON(); + + DR_Sub t = new DR_Sub( j ); + + assertTrue( un.equals( t.getUsername() )); + assertTrue( up.equals( t.getUserpwd() )); + //assertTrue( f.equals( t.getFeedId() )); + assertTrue( du.equals( t.getDeliveryURL() ) ); + //assertTrue( lu.equals( t.getLogURL() ) ); + assertTrue( ! t.isSuspended() ); + + } + + @Test + public void testJSONfromATT() { + + + DR_Sub s = new DR_Sub( d, un, up, f, du, lu, u100 ); + + DR_Sub t = new DR_Sub( s.toProvJSONforATT() ); + + assertTrue( un.equals( t.getUsername() )); + assertTrue( up.equals( t.getUserpwd() )); + //assertTrue( f.equals( t.getFeedId() )); + assertTrue( du.equals( t.getDeliveryURL() ) ); + // assertTrue( lu.equals( t.getLogURL() ) ); + assertTrue( ! t.isSuspended() ); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DcaeLocationTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DcaeLocationTest.java new file mode 100644 index 0000000..6652bb0 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DcaeLocationTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +public class DcaeLocationTest { + String c, dl, dln, osz, s, edge; + + @Before + public void setUp() throws Exception { + c = "ABCDE888NJ"; + dl = "central-node"; + edge = "local-node"; + dln = "hollywood"; + osz = "california"; + s = "10.10.10.1"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testDcaeLocationDefaultConstructor() { + + DcaeLocation t = new DcaeLocation(); + + assertTrue( t.getClli() == null ); + assertTrue( t.getDcaeLayer() == null ); + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getOpenStackAvailabilityZone() == null ); + assertTrue( t.getSubnet() == null ); + + } + + @Test + public void testDcaeLocationClassConstructor() { + + DcaeLocation t = new DcaeLocation( c, dl, dln, osz, s ); + + assertTrue( c.equals( t.getClli() )); + assertTrue( dl.equals( t.getDcaeLayer() )); + assertTrue( dln.equals( t.getDcaeLocationName() )); + assertTrue( osz.equals( t.getOpenStackAvailabilityZone() )); + assertTrue( s.equals( t.getSubnet() )); + } + + @Test + public void testDmaapClassSetters() { + + DcaeLocation t = new DcaeLocation(); + + t.setClli( c ); + assertTrue( c.equals( t.getClli() )); + t.setDcaeLayer( dl ); + assertTrue( dl.equals( t.getDcaeLayer() )); + assertTrue( t.isCentral() ); + t.setDcaeLayer( edge ); + assertTrue( edge.equals( t.getDcaeLayer() )); + assertTrue( t.isLocal() ); + t.setDcaeLocationName( dln ); + assertTrue( dln.equals( t.getDcaeLocationName() )); + t.setOpenStackAvailabilityZone( osz ); + assertTrue( osz.equals( t.getOpenStackAvailabilityZone() )); + t.setSubnet( s ); + assertTrue( s.equals( t.getSubnet() )); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java new file mode 100644 index 0000000..cb0c22f --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DmaapTest { + private String ver, tnr, dn, dpu, lu, bat, nk, ako; + + @Before + public void setUp() throws Exception { + ver = "1"; + tnr = "org.onap.dmaap"; + dn = "onap"; + dpu = "https://drps.dmaap.onap.org:8081"; + lu = "http://drps.dmaap.onap.org:8080/feedlog"; + bat = "org.onap.dcae.dmaap.MM_AGENT_TOPIC"; + nk = "foo"; + ako = "bar"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testDmaapClassDefaultConstructor() { + + Dmaap t = new Dmaap.DmaapBuilder().createDmaap(); + + assertTrue( t.getVersion() == null ); + assertTrue( t.getTopicNsRoot() == null ); + assertTrue( t.getDmaapName() == null ); + assertTrue( t.getDrProvUrl() == null ); + assertTrue( t.getLoggingUrl() == null ); + assertTrue( t.getBridgeAdminTopic() == null ); + assertTrue( t.getNodeKey() == null ); + assertTrue( t.getAccessKeyOwner() == null ); + + } + + @Test + public void testDmaapClassConstructor() { + + Dmaap t = new Dmaap.DmaapBuilder().setVer(ver).setTnr(tnr).setDn(dn).setDpu(dpu).setLu(lu).setBat(bat).setNk(nk).setAko(ako).createDmaap(); + + assertTrue( ver.equals( t.getVersion() )); + assertTrue( tnr.equals( t.getTopicNsRoot() )); + assertTrue( dn.equals( t.getDmaapName() )); + assertTrue( dpu.equals( t.getDrProvUrl() )); + assertTrue( lu.equals( t.getLoggingUrl() )); + assertTrue( bat.equals( t.getBridgeAdminTopic() )); + assertTrue( nk.equals( t.getNodeKey() )); + assertTrue( ako.equals( t.getAccessKeyOwner() )); + + } + + @Test + public void testDmaapClassSetters() { + + Dmaap t = new Dmaap.DmaapBuilder().createDmaap(); + + t.setVersion( ver ); + assertTrue( ver.equals( t.getVersion() )); + t.setTopicNsRoot( tnr ); + assertTrue( tnr.equals( t.getTopicNsRoot() )); + t.setDmaapName( dn ); + assertTrue( dn.equals( t.getDmaapName() )); + t.setDrProvUrl( dpu ); + assertTrue( dpu.equals( t.getDrProvUrl() )); + t.setLoggingUrl( lu ); + assertTrue( lu.equals( t.getLoggingUrl() )); + t.setBridgeAdminTopic( bat ); + assertTrue( bat.equals( t.getBridgeAdminTopic() )); + t.setNodeKey( nk ); + assertTrue( nk.equals( t.getNodeKey() )); + t.setAccessKeyOwner( ako ); + assertTrue( ako.equals( t.getAccessKeyOwner() )); + + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/FeedTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/FeedTest.java new file mode 100644 index 0000000..4fdc9a1 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/FeedTest.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import java.util.ArrayList; + + +public class FeedTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + String n, v, d, o, a; + + @Before + public void setUp() throws Exception { + System.setProperty("ConfigFile", "src/test/resources/dmaapbc.properties"); + n = "Chicken Feed"; + v = "1.0"; + d = "A daily helping of chicken eating metrics"; + o = "ab123"; + a = "Unrestricted"; + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.model.Feed", "get", null ); + + } + + @Test + public void test2() { + Feed t = new Feed( n, v, d, o, a ); + + ArrayList<DR_Sub> subs = new ArrayList<DR_Sub>(); + DR_Sub sub = new DR_Sub( "central", "user", "pwd", "22", "server.onap.org/deliv", "log.onap.org/logs", true ); + subs.add( sub ); + t.setSubs( subs ); + + assertTrue( n.equals( t.getFeedName() )); + assertTrue( v.equals( t.getFeedVersion() )); + assertTrue( d.equals( t.getFeedDescription() )); + assertTrue( o.equals( t.getOwner() )); + assertTrue( a.equals( t.getAsprClassification() ) ); + assertTrue( ! t.isSuspended() ); + } + + @Test + public void test3() { + + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.model.Feed", "set", v ); + } + + @Test + public void test4() { + String s = String.format( "{ \"%s\": \"%s\", \"%s\": \"%s\", \"%s\": \"%s\", \"%s\": \"%s\", \"%s\": false, \"%s\": { \"%s\": \"%s\", \"%s\": \"%s\", \"%s\": \"%s\" }, \"%s\": { \"%s\": \"%s\", \"%s\": [ { \"%s\": \"%s\", \"%s\": \"%s\" } ] } }", + "name", n, + "version", v, + "description", d, + "publisher", a, + "suspend", + "links", + "publish", "https://feed.onap.org/publish/22", + "subscribe" , Feed.getSubProvURL( "22" ), + "log" , "https://feed.onap.org/log/22", + "authorization", + "classification", a, + "endpoint_ids" , "id", "king", "password", "henry" ); + + + Feed t = new Feed( s ); + + assertTrue( n.equals( t.getFeedName() )); + assertTrue( v.equals( t.getFeedVersion() )); + assertTrue( d.equals( t.getFeedDescription() )); + assertTrue( a.equals( t.getAsprClassification() ) ); + assertTrue( ! t.isSuspended() ); + + String o = t.toString(); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/JUnitTestSuite.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/JUnitTestSuite.java new file mode 100644 index 0000000..69e1b69 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/JUnitTestSuite.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import ch.qos.logback.classic.Logger; +import junit.framework.TestSuite; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({DmaapTest.class}) +public class JUnitTestSuite { + + static Logger logger; + + public static void main(String[] args) { + logger.info("Running the test suite"); + + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MRClientTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MRClientTest.java new file mode 100644 index 0000000..ba95a85 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MRClientTest.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019 IBM. + * ================================================================================ + * 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.dbcapi.model; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class MRClientTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + String d, t, f, c, m; + + @Before + public void setUp() throws Exception { + d = "central-onap"; + t = "org.onap.dmaap.interestingTopic"; + f = "mrc.onap.org:3904/events/org.onap.dmaap.interestingTopic"; + c = "publisher"; + m = "m12345"; + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test1() { + + // can't use simple reflection to test for null since null constructor + // initializes some fields. + // rh.reflect( "org.onap.dmaap.dbcapi.model.MR_Client", "get", null ); + // so brute force instead... + String[] a = { "put", "view" }; + MR_Client m = new MR_Client(); + + assertTrue(null == m.getDcaeLocationName()); + assertTrue(null == m.getFqtn()); + assertTrue(null == m.getClientRole()); + assertTrue(null == m.getAction()); + + } + + @Test + public void test2() { + String[] a = { "put", "view" }; + MR_Client m = new MR_Client(d, f, c, a); + + assertTrue(d.equals(m.getDcaeLocationName())); + assertTrue(f.equals(m.getFqtn())); + assertTrue(c.equals(m.getClientRole())); + String[] ma = m.getAction(); + assertTrue(a.length == ma.length); + for (int i = 0; i < a.length; i++) { + assertTrue(a[i].equals(ma[i])); + } + } + + @Test + public void test3() { + + String v = "Validate"; + rh.reflect("org.onap.dmaap.dbcapi.model.MR_Client", "set", v); + } + + @Test + public void test4() { + MR_Client mrClient = new MR_Client(); + String stringArray[] = { "test" }; + mrClient.setAction(stringArray); + mrClient.hasAction(""); + mrClient.setMrClientId("mrClientId"); + mrClient.setTopicURL("testTopicURL"); + mrClient.setClientIdentity("clientIdentity"); + + assertEquals("clientIdentity", mrClient.getClientIdentity()); + assertEquals("testTopicURL", mrClient.getTopicURL()); + assertEquals("mrClientId", mrClient.getMrClientId()); + assertEquals(false, mrClient.isPublisher()); + assertEquals(false, mrClient.isSubscriber()); + assertEquals("test", mrClient.getAction()[0]); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MR_ClusterTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MR_ClusterTest.java new file mode 100644 index 0000000..2200627 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MR_ClusterTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; +public class MR_ClusterTest { + String d, fqdn, repGrp, p1, p2, prot, p0; + + ReflectionHarness rh = new ReflectionHarness(); + + @Before + public void setUp() throws Exception { + d = "central-onap"; + fqdn = "mr.onap.org"; + repGrp = "zeppelin"; + prot = "http"; + p0 = "3904"; + p1 = "9092"; + p2 = "2323"; + + + + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testMR_ClusterClassDefaultConstructor() { + + MR_Cluster t = new MR_Cluster(); + + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getFqdn() == null ); + + } + + @Test + public void testMR_ClusterClassConstructor() { + + MR_Cluster t = new MR_Cluster( d, fqdn, prot, p0); + + assertTrue( t.getDcaeLocationName() == d ); + assertTrue( t.getFqdn() == fqdn ); + assertTrue( t.getTopicProtocol() == prot ); + assertTrue( t.getTopicPort() == p0 ); + + // pass null params to trigger default settings + t = new MR_Cluster( d, fqdn, null, null ); + + assertTrue( t.getDcaeLocationName() == d ); + assertTrue( t.getFqdn() == fqdn ); + assertTrue( t.getTopicProtocol() != null ); + assertTrue( t.getTopicPort() != null ); + } + + @Test + public void testMR_ClusterManyArgsClassConstructor() { + + MR_Cluster t = new MR_Cluster( d, fqdn, prot, p0, repGrp, p1, p2 ); + + assertTrue( t.getDcaeLocationName() == d ); + assertTrue( t.getFqdn() == fqdn ); + assertTrue( t.getTopicProtocol() == prot ); + assertTrue( t.getTopicPort() == p0 ); + assertTrue( t.getReplicationGroup() == repGrp ); + assertTrue( t.getSourceReplicationPort() == p1 ); + assertTrue( t.getTargetReplicationPort() == p2 ); + + // pass null params to trigger default settings + t = new MR_Cluster( d, fqdn, null, null, null, null, null ); + + assertTrue( t.getDcaeLocationName() == d ); + assertTrue( t.getFqdn() == fqdn ); + assertTrue( t.getTopicProtocol() != null ); + assertTrue( t.getTopicPort() != null ); + assertTrue( t.getReplicationGroup() != null ); + assertTrue( t.getSourceReplicationPort() != null ); + assertTrue( t.getTargetReplicationPort() != null ); + } + + @Test + public void testw3() { + + MR_Cluster t = new MR_Cluster(); + + assertTrue( t.getDcaeLocationName() == null ); + assertTrue( t.getFqdn() == null ); + + String override = "cluster2.onap.org"; + String topic2 = "org.onap.topic2"; + String fqtn = t.genTopicURL( override, topic2 ); + assertTrue( fqtn.contains( override) && fqtn.contains(topic2)); + + fqtn = t.genTopicURL( null, "org.onap.topic2" ); + assertTrue(fqtn.contains(topic2)); + } + + + + @Test + public void testsetter() { + + String v = "validate"; + + + rh.reflect( "org.onap.dmaap.dbcapi.model.MR_Cluster", "set", v ); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MirrorMakerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MirrorMakerTest.java new file mode 100644 index 0000000..39de2be --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/MirrorMakerTest.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import java.util.ArrayList; + + +public class MirrorMakerTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.model.MirrorMaker", "get", null ); + + } + @Test + public void test2() { + + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.model.MirrorMaker", "set", v ); + } + + @Test + public void test3() { + String f = "org.onap.interestingTopic"; + String c1 = "cluster1.onap.org"; + String c2 = "cluster2.onap.org"; + MirrorMaker t = new MirrorMaker( c1, c2 ); + String m = t.getMmName(); + + MirrorMaker.genKey( c1, c2 ); + + assertTrue( c1.equals( t.getSourceCluster() )); + assertTrue( c2.equals( t.getTargetCluster() )); + } + + + @Test + public void test4() { + String f = "org.onap.interestingTopic"; + String c1 = "cluster1.onap.org"; + String c2 = "cluster2.onap.org"; + String p1 = "9092"; + String p2 = "2081"; + MirrorMaker t = new MirrorMaker( c1, c2 ); + String m = t.getMmName(); + + + ArrayList<String> topics = new ArrayList<String>(); + topics.add( f ); + t.setTopics( topics ); + t.addTopic( "org.onap.topic2" ); + + int i = t.getTopicCount(); + + String s = t.getWhitelistUpdateJSON(); + + s = t.createMirrorMaker(p1, p2); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TestRunner.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TestRunner.java new file mode 100644 index 0000000..16b48e3 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TestRunner.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.model; + +import ch.qos.logback.classic.Logger; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; + +public class TestRunner extends BaseLoggingClass { + + private static Logger logger; + + public static void main(String[] args) { + + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); + + } + logger.info(String.valueOf(result.wasSuccessful())); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TopicTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TopicTest.java new file mode 100644 index 0000000..5da3aed --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/model/TopicTest.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 IBM + * ================================================================================ + * 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.dbcapi.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class TopicTest { + + ReflectionHarness rh = new ReflectionHarness(); + + String f, t, d, e, o; + + @Before + public void setUp() throws Exception { + f = "org.onap.dmaap.interestingTopic"; + t = "interestingTopic"; + d = "A so very interesting topic"; + e = "Yes"; + o = "m12345"; + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test1() { + rh.reflect("org.onap.dmaap.dbcapi.model.Topic", "get", null); + } + + @Test + public void test2() { + Topic obj = new Topic(f, t, d, e, o); + assertTrue(f.equals(obj.getFqtn())); + assertTrue(t.equals(obj.getTopicName())); + assertTrue(d.equals(obj.getTopicDescription())); + assertTrue(e.equals(obj.getTnxEnabled())); + assertTrue(o.equals(obj.getOwner())); + } + + @Test + public void test3() { + String v = "Validate"; + rh.reflect("org.onap.dmaap.dbcapi.model.Topic", "set", v); + } + + @Test + public void getNumClientsHavingMRClientListNull() { + Topic obj = new Topic(f, t, d, e, o); + obj.setClients(null); + assertEquals(0, obj.getNumClients()); + } + + @Test + public void testTopicInitializationWithInvalidJsonString() { + String json = "{\"key\":\"value\""; + Topic obj = new Topic(json); + assertEquals(DmaapObject_Status.INVALID, obj.getStatus()); + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthenticationFilterTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthenticationFilterTest.java new file mode 100644 index 0000000..76fe914 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthenticationFilterTest.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +@RunWith(MockitoJUnitRunner.class) +public class AAFAuthenticationFilterTest { + + @Spy + private AAFAuthenticationFilter filter; + @Mock + private FilterConfig filterConfig; + @Mock + private CadiFilter cadiFilterMock; + @Mock + private HttpServletRequest servletRequest; + @Mock + private HttpServletResponse servletResponse; + @Mock + private FilterChain filterChain; + @Mock + private DmaapConfig dmaapConfig; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + doReturn(dmaapConfig).when(filter).getConfig(); + } + + @Test + public void init_shouldNotInitializeCADI_whenAafIsNotUsed() throws Exception { + //given + doReturn("false").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + + //when + filter.init(filterConfig); + + //then + assertFalse(filter.isCadiEnabled()); + assertNull(filter.getCadiFilter()); + } + + @Test + public void doFilter_shouldSkipCADI_whenAafIsNotUsed() throws Exception { + //given + doReturn("false").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + filter.init(filterConfig); + filter.setCadiFilter(cadiFilterMock); + + //when + filter.doFilter(servletRequest, servletResponse, filterChain); + + //then + verify(filterChain).doFilter(servletRequest,servletResponse); + verifyZeroInteractions(cadiFilterMock,servletRequest,servletResponse); + } + + @Test + public void init_shouldFail_whenAafIsUsed_andCadiPropertiesHasNotBeenSet() throws Exception { + //given + doReturn("true").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + doReturn("").when(dmaapConfig).getProperty(AAFAuthenticationFilter.CADI_PROPERTIES); + + //then + thrown.expect(ServletException.class); + thrown.expectMessage("Cannot initialize CADI filter.CADI properties not available."); + + //when + filter.init(filterConfig); + } + + @Test + public void init_shouldFail_whenAafIsUsed_andInvalidCadiPropertiesSet() throws Exception { + //given + String invalidFilePath = "src/test/resources/notExisting.properties"; + doReturn("true").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + doReturn(invalidFilePath).when(dmaapConfig).getProperty(AAFAuthenticationFilter.CADI_PROPERTIES); + + //then + thrown.expect(ServletException.class); + thrown.expectMessage("Could not load CADI properties file: "+invalidFilePath); + + //when + filter.init(filterConfig); + } + + /* + * See https://jira.onap.org/browse/DMAAP-1361 for why this is commented out + @Test + public void init_shouldInitializeCADI_whenAafIsUsed_andValidCadiPropertiesSet() throws Exception { + //given + doReturn("true").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + doReturn("src/test/resources/cadi.properties").when(dmaapConfig).getProperty(AAFAuthenticationFilter.CADI_PROPERTIES); + + //when + filter.init(filterConfig); + + //then + assertTrue(filter.isCadiEnabled()); + assertNotNull(filter.getCadiFilter()); + } + + @Test + public void doFilter_shouldUseCADIfilter_andAuthenticateUser_whenAAFisUsed_andUserIsValid() throws Exception{ + //given + initCADIFilter(); + doReturn(200).when(servletResponse).getStatus(); + + //when + filter.doFilter(servletRequest,servletResponse,filterChain); + + //then + verify(cadiFilterMock).doFilter(servletRequest,servletResponse,filterChain); + verify(servletResponse).getStatus(); + verifyNoMoreInteractions(servletResponse); + verifyZeroInteractions(filterChain, servletRequest); + } + + @Test + public void doFilter_shouldUseCADIfilter_andReturnAuthenticationError_whenAAFisUsed_andUserInvalid() throws Exception{ + //given + String errorResponseJson = "{\"code\":401,\"message\":\"invalid or no credentials provided\",\"fields\":\"Authentication\",\"2xx\":false}"; + initCADIFilter(); + doReturn(401).when(servletResponse).getStatus(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + doReturn(pw).when(servletResponse).getWriter(); + + //when + filter.doFilter(servletRequest,servletResponse,filterChain); + + //then + verify(cadiFilterMock).doFilter(servletRequest,servletResponse,filterChain); + verify(servletResponse).getStatus(); + verify(servletResponse).setContentType("application/json"); + verifyZeroInteractions(filterChain, servletRequest); + assertEquals(errorResponseJson, sw.toString()); + } + + private void initCADIFilter() throws Exception{ + doReturn("true").when(dmaapConfig).getProperty(eq(AAFAuthenticationFilter.CADI_AUTHN_FLAG), anyString()); + doReturn("src/test/resources/cadi.properties").when(dmaapConfig).getProperty(AAFAuthenticationFilter.CADI_PROPERTIES); + filter.init(filterConfig); + filter.setCadiFilter(cadiFilterMock); + } +*/ +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthorizationFilterTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthorizationFilterTest.java new file mode 100644 index 0000000..ba11b01 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/AAFAuthorizationFilterTest.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import java.io.PrintWriter; +import java.io.StringWriter; +import com.sun.security.auth.UserPrincipal; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.service.DmaapService; +import org.onap.dmaap.dbcapi.util.DmaapConfig; +import org.onap.dmaap.dbcapi.util.PermissionBuilder; + +@RunWith(MockitoJUnitRunner.class) +public class AAFAuthorizationFilterTest { + + @Spy + private AAFAuthorizationFilter filter; + @Mock + private FilterConfig filterConfig; + @Mock + private HttpServletRequest servletRequest; + @Mock + private HttpServletResponse servletResponse; + @Mock + private FilterChain filterChain; + @Mock + private DmaapConfig dmaapConfig; + @Mock + private PermissionBuilder permissionBuilder; + @Mock + private DmaapService dmaapService; + + @Before + public void setUp() throws Exception { + filter.setPermissionBuilder(permissionBuilder); + doReturn(dmaapConfig).when(filter).getConfig(); + doReturn(dmaapService).when(filter).getDmaapService(); + } + + @Test + public void init_shouldNotInitializePermissionBuilder_whenAAFnotUsed() throws Exception { + //given + filter.setPermissionBuilder(null); + configureAAFUsage(false); + + //when + filter.init(filterConfig); + + //then + assertNull(filter.getPermissionBuilder()); + } + + @Test + public void init_shouldInitializePermissionBuilder_whenAAFisUsed() throws Exception { + //given + filter.setPermissionBuilder(null); + configureAAFUsage(true); + //doReturn(provideEmptyInstance()).when(dmaapService).getDmaap(); + when(dmaapService.getDmaap()).thenReturn(mock(Dmaap.class)); + + //when + filter.init(filterConfig); + + //then + assertNotNull(permissionBuilder); + } + + @Test + public void doFilter_shouldSkipAuthorization_whenAAFnotUsed() throws Exception { + //given + filter.setCadiEnabled(false); + + //when + filter.doFilter(servletRequest,servletResponse,filterChain); + + //then + verify(filterChain).doFilter(servletRequest,servletResponse); + verifyNoMoreInteractions(filterChain); + verifyZeroInteractions(permissionBuilder, servletRequest, servletResponse); + } + + @Test + public void doFilter_shouldPass_whenUserHasPermissionToResourceEndpoint() throws Exception { + //given + String user = "johnny"; + String permission = "org.onap.dmaap-bc.api.topics|mr|GET"; + when(permissionBuilder.buildPermission(servletRequest)).thenReturn(permission); + configureServletRequest(permission, user, true); + filter.setCadiEnabled(true); + + //when + filter.doFilter(servletRequest,servletResponse,filterChain); + + //then + verify(filterChain).doFilter(servletRequest,servletResponse); + verify(permissionBuilder).updateDmaapInstance(); + verifyZeroInteractions(servletResponse); + } + + @Test + public void doFilter_shouldReturnError_whenUserDontHavePermissionToResourceEndpoint() throws Exception { + //given + String user = "jack"; + String permission = "org.onap.dmaap-bc.api.topics|mr|GET"; + when(permissionBuilder.buildPermission(servletRequest)).thenReturn(permission); + configureServletRequest(permission, user, false); + filter.setCadiEnabled(true); + + String errorMsgJson = "{\"code\":403,\"message\":\"User "+user+" does not have permission " + + permission +"\",\"fields\":\"Authorization\",\"2xx\":false}"; + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + when(servletResponse.getWriter()).thenReturn(pw); + + //when + filter.doFilter(servletRequest,servletResponse,filterChain); + + //then + verifyZeroInteractions(filterChain); + verify(permissionBuilder).updateDmaapInstance(); + verify(servletResponse).setStatus(403); + assertEquals(errorMsgJson, sw.toString()); + } + + private void configureServletRequest(String permission, String user, boolean isUserInRole) { + when(servletRequest.getUserPrincipal()).thenReturn(new UserPrincipal(user)); + when(servletRequest.isUserInRole(permission)).thenReturn(isUserInRole); + } + + private void configureAAFUsage(Boolean isUsed) { + doReturn(isUsed.toString()).when(dmaapConfig).getProperty(eq(AAFAuthorizationFilter.CADI_AUTHZ_FLAG), anyString()); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_NodeResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_NodeResourceTest.java new file mode 100644 index 0000000..f131d8f --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_NodeResourceTest.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; + +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Node; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class DR_NodeResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + private static FastJerseyTestContainer testContainer; + + @BeforeClass + public static void setUpClass() throws Exception { + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(DR_NodeResource.class)); + testContainer.init(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.clearDatabase(); + DatabaseClass.getDmaap().remove();*/ + } + + @Test + public void getDr_Nodes_test() { + Response response = testContainer.target("dr_nodes").request().get(Response.class); + System.out.println("GET dr_subs response=" + response.getStatus()); + + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + } + + @Test + public void addDr_Node_shouldReturnError_whenNoLocationAndFqdnProvided() { + DR_Node node = new DR_Node(null, null, "hostName", "1.0"); + Entity<DR_Node> requestedEntity = entity(node, APPLICATION_JSON); + + Response response = testContainer.target("dr_nodes") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocation, fqdn", responseError.getFields()); + } + + @Test + public void addDr_Node_shouldReturnError_whenDrNodeWithGiveFqdnAlreadyExists() { + DR_Node node = new DR_Node("fqdn", "location", "hostName", "1.0"); + + addDrNode(node); + Response response = addDrNode(node); + + assertEquals(409, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqdn", responseError.getFields()); + assertEquals("Node fqdn already exists", responseError.getMessage()); + } + + @Test + public void addDr_Node_shouldExecuteSuccessfully() { + DR_Node node = new DR_Node("fqdn", "location", "hostName", "1.0"); + + Response response = addDrNode(node); + + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertDrNodeExistInDB(response.readEntity(DR_Node.class)); + } + + @Test + public void updateDr_Node_shouldReturnError_whenNoLocationAndFqdnProvided() { + DR_Node node = new DR_Node(null, null, "hostName", "1.0"); + Entity<DR_Node> requestedEntity = entity(node, APPLICATION_JSON); + + Response response = testContainer.target("dr_nodes") + .path("fqdn") + .request() + .put(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocation, fqdn", responseError.getFields()); + } + + @Test + public void updateDr_Node_shouldReturnError_whenDrNodeForUpdateDoesNotExistInDb() { + DR_Node node = new DR_Node("fqdn", "location", "hostName", "1.0"); + Entity<DR_Node> requestedEntity = entity(node, APPLICATION_JSON); + + Response response = testContainer.target("dr_nodes") + .path(node.getFqdn()) + .request() + .put(requestedEntity, Response.class); + + assertEquals(404, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqdn", responseError.getFields()); + assertEquals("Node " + node.getFqdn() + " does not exist", responseError.getMessage()); + } + + @Test + public void updateDr_Node_ShouldExecuteSuccessfully() { + DR_Node toUpdate = new DR_Node("fqdn", "location", "hostName", "1.0"); + Entity<DR_Node> requestedEntity = entity(toUpdate, APPLICATION_JSON); + + addDrNode(new DR_Node("fqdn", "old_location", "old_hostName", "old_1.0")); + Response response = testContainer.target("dr_nodes") + .path(toUpdate.getFqdn()) + .request() + .put(requestedEntity, Response.class); + + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertEquals(toUpdate, response.readEntity(DR_Node.class)); + } + + @Test + public void deleteDr_Node_shouldReturnError_whenDrNodeForDeleteDoesNotExistInDb() { + Response response = testContainer.target("dr_nodes") + .path("fqdn") + .request() + .delete(); + + assertEquals(404, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqdn", responseError.getFields()); + assertEquals("Node fqdn does not exist", responseError.getMessage()); + } + + @Test + public void deleteDr_Node_shouldReturnError_whenNoExistingFqdnProvided() { + Response response = testContainer.target("dr_nodes") + .path("") + .request() + .delete(); + + assertEquals(405, response.getStatus()); + } + + @Test + public void deleteDr_Node_shouldExecuteSuccessfully() { + DR_Node node = new DR_Node("fqdn", "location", "hostName", "1.0"); + + addDrNode(node); + Response response = testContainer.target("dr_nodes") + .path("fqdn") + .request() + .delete(); + + assertEquals(204, response.getStatus()); + } + + @Test + public void getDr_Node_shouldReturnError_whenDrNodeForDeleteDoesNotExistInDb() { + Response response = testContainer.target("dr_nodes") + .path("fqdn") + .request() + .get(); + + assertEquals(404, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqdn", responseError.getFields()); + assertEquals("Node fqdn does not exist", responseError.getMessage()); + } + + private Response addDrNode(DR_Node node) { + return testContainer.target("dr_nodes") + .request() + .post(entity(node, APPLICATION_JSON), Response.class); + } + + private void assertDrNodeExistInDB(DR_Node created) { + Response response = testContainer.target("dr_nodes") + .path(created.getFqdn()) + .request() + .get(); + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertEquals(created, response.readEntity(DR_Node.class)); + } + + @Before + public void cleanupDatabase() { + DatabaseClass.clearDatabase(); + } + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_PubResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_PubResourceTest.java new file mode 100644 index 0000000..340f362 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_PubResourceTest.java @@ -0,0 +1,291 @@ + +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Pub; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +public class DR_PubResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + + private static final String DCAE_LOCATION_NAME = "central-onap"; + private static final String USERNAME = "user1"; + private static final String USRPWD = "secretW0rd"; + private static final String FEED_ID = "someFakeFeedId"; + private static final String PUB_ID = "0"; + private static FastJerseyTestContainer testContainer; + private static TestFeedCreator testFeedCreator; + + @BeforeClass + public static void setUpClass() throws Exception { + //TODO: init is still needed here to assure that dmaap is not null + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(DmaapResource.class) + .register(DR_PubResource.class) + .register(FeedResource.class)); + + testContainer.init(); + testFeedCreator = new TestFeedCreator(testContainer); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.clearDatabase(); + DatabaseClass.getDmaap().remove();*/ + } + + @Before + public void cleanupDatabase() { + DatabaseClass.clearDatabase(); + } + + @Test + public void getDr_Pub_test() { + Response resp = testContainer.target("dr_pubs").request().get(Response.class); + assertTrue(resp.getStatus() == 200); + assertTrue(resp.hasEntity()); + } + + @Test + public void addDr_Pub_shallReturnError_whenNoFeedIdAndFeedNameInPubProvided() { + //given + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, PUB_ID); + Entity<DR_Pub> requestedEntity = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Pub_shallReturnError_whenFeedNameProvided_butFeedNotExist() { + //given + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, PUB_ID); + Entity<DR_Pub> requestedEntity = Entity.entity(drPub, MediaType.APPLICATION_JSON); + drPub.setFeedName("feed_name"); + + + //when + Response resp = testContainer.target("dr_pubs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + + } + + @Test + public void addDr_Pub_shallReturnError_whenFeedIdProvided_butFeedNotExist() { + //given + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, FEED_ID, PUB_ID); + Entity<DR_Pub> requestedEntity = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedId=" + FEED_ID, responseError.getFields()); + } + + @Test + public void addDr_Pub_shallExecuteSuccessfully_whenValidFeedIdProvided() { + //given + String feedId = assureFeedIsInDB(); + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + Entity<DR_Pub> requestedEntity = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + } + + @Test + public void addDr_Pub_shallExecuteSuccessfully_whenValidFeedNameProvided() { + //given + String feedName = "testFeed"; + testFeedCreator.addFeed(feedName, "test feed"); + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, PUB_ID); + drPub.setFeedName(feedName); + Entity<DR_Pub> requestedEntity = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + } + + @Test + public void updateDr_Pub_shallExecuteSuccessfully_whenAddingNewPublisher() { + //given + String pubId = "5"; + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, "feedId", PUB_ID); + Entity<DR_Pub> reqEntity2 = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .path(pubId) + .request() + .put(reqEntity2, Response.class); + + //then + assertEquals(200, resp.getStatus()); + + } + /*// + // When this test is included, the following error is generated: + Exception in thread "HTTP-Dispatcher" java.lang.AssertionError: State is not RESPONSE (REQUEST) + at jdk.httpserver/sun.net.httpserver.ServerImpl.responseCompleted(ServerImpl.java:814) + at jdk.httpserver/sun.net.httpserver.ServerImpl$Dispatcher.handleEvent(ServerImpl.java:297) + at jdk.httpserver/sun.net.httpserver.ServerImpl$Dispatcher.run(ServerImpl.java:356) + at java.base/java.lang.Thread.run(Thread.java:830) +// I can't figure it out, so created a Jira for now. DMAAP-1358 + @Test + public void updateDr_Pub_shallReturnError_whenPathIsWrong() { + //given + DR_Pub drPub = new DR_Pub(DCAE_LOCATION_NAME, USERNAME, USRPWD, FEED_ID, PUB_ID); + Entity<DR_Pub> reqEntity2 = Entity.entity(drPub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_pubs") + .path("") + .request() + .put(reqEntity2, Response.class); + + //then + assertEquals(405, resp.getStatus()); + }*/ + @Test + public void deleteDr_Pub_shouldDeleteObjectWithSuccess() { + //given + String feedId = assureFeedIsInDB(); + DR_Pub dr_pub = addPub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_pubs") + .path(dr_pub.getPubId()) + .request() + .delete(); + + //then + assertEquals("Shall delete publisher with success", 204, resp.getStatus()); + assertFalse("No entity object shall be returned", resp.hasEntity()); + } + + @Test + public void deleteDr_Pub_shouldReturnErrorResponse_whenGivenPubIdNotFound() { + //given + String notExistingPubId = "6789"; + + //when + Response resp = testContainer.target("dr_pubs") + .path(notExistingPubId) + .request() + .delete(); + + //then + assertEquals("Shall return error, when trying to delete not existing publisher", 404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("pubId", responseError.getFields()); + } + + @Test + public void get_shallReturnExistingObject() { + //given + String feedId = assureFeedIsInDB(); + DR_Pub dr_Pub = addPub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_pubs") + .path(dr_Pub.getPubId()) + .request() + .get(); + + //then + assertEquals("Publisher shall be found", 200, resp.getStatus()); + assertEquals("Retrieved object shall be equal to eh one put into DB", dr_Pub, resp.readEntity(DR_Pub.class)); + } + + private DR_Pub addPub(String d, String un, String up, String feedId) { + DR_Pub dr_pub = new DR_Pub(d, un, up, feedId, ""); + Entity<DR_Pub> reqEntity2 = Entity.entity(dr_pub, MediaType.APPLICATION_JSON); + Response resp = testContainer.target("dr_pubs").request().post(reqEntity2, Response.class); + System.out.println("POST dr_pubs resp=" + resp.getStatus()); + assertTrue(resp.getStatus() == 201); + dr_pub = resp.readEntity(DR_Pub.class); + return dr_pub; + } + + private String assureFeedIsInDB() { + Feed feed = testFeedCreator.addFeed("PublisherTestFeed", "feed for DR_Pub testing"); + assertNotNull("Feed shall be added into DB properly", feed); + return feed.getFeedId(); + } + + +} + + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java new file mode 100644 index 0000000..13b89ea --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java @@ -0,0 +1,434 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Sub; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +public class DR_SubResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + + private static final String DCAE_LOCATION_NAME = "central-onap"; + private static final String USERNAME = "user1"; + private static final String USRPWD = "secretW0rd"; + private static final String DELIVERY_URL = "https://subscriber.onap.org/delivery/id"; + private static final String LOG_URL = "https://dr-prov/sublog/id"; + private static final String DELIVERY_URL_TEMPLATE = "https://subscriber.onap.org/delivery/"; + private static final String LOG_URL_TEMPLATE = "https://dr-prov/sublog/"; + private static FastJerseyTestContainer testContainer; + private static TestFeedCreator testFeedCreator; + + @BeforeClass + public static void setUpClass() throws Exception { + //TODO: init is still needed here to assure that dmaap is not null + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(DR_SubResource.class) + .register(FeedResource.class)); + testContainer.init(); + testFeedCreator = new TestFeedCreator(testContainer); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.clearDatabase(); + DatabaseClass.getDmaap().remove();*/ + } + + @Before + public void cleanupDatabase() { + DatabaseClass.clearDatabase(); + } + + //TODO: figure out generic entity list unmarshall to check the entity list + @Test + public void getDr_Subs_test() { + Response resp = testContainer.target("dr_subs").request().get(Response.class); + System.out.println("GET dr_subs resp=" + resp.getStatus()); + + assertEquals(200, resp.getStatus()); + assertTrue(resp.hasEntity()); + } + + @Test + public void addDr_Sub_shallReturnError_whenNoFeedIdAndFeedNameInSubProvided() { + //given + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedNameProvided_butFeedNotExist() { + //given + String notExistingFeedName = "notRealFead"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(notExistingFeedName); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedNameProvided_andManyFeedsWithTheSameNameInDB() { + //given + String notDistinctFeedName = "notDistinctFeedName"; + Feed feed1 = new Feed(notDistinctFeedName, "1.0", "description", "dgl", "unrestricted"); + Feed feed2 = new Feed(notDistinctFeedName, "2.0", "description", "dgl", "unrestricted"); + DatabaseClass.getFeeds().put("1", feed1); + DatabaseClass.getFeeds().put("2", feed2); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(notDistinctFeedName); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(409, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedIdProvided_butFeedNotExist() { + //given + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, "someFakeFeedId", DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertTrue(responseError.getFields().contains("feedId")); + } + + @Test + public void addDr_Sub_shallExecuteSuccessfully_whenValidFeedIdProvided() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId, DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + assertTrue(resp.hasEntity()); + DR_Sub created = resp.readEntity(DR_Sub.class); + assertSubscriptionExistInDB(created); + } + + @Test + public void addDr_Sub_shallExecuteSuccessfully_whenValidFeedNameProvided() { + //given + String feedName = "testFeed"; + testFeedCreator.addFeed(feedName, "test feed"); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(feedName); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + assertTrue(resp.hasEntity()); + DR_Sub created = resp.readEntity(DR_Sub.class); + assertSubscriptionExistInDB(created); + } + + + @Test + public void updateDr_Sub_shallReturnError_whenNoFeedIdInSubProvided() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedId", responseError.getFields()); + } + + @Test + public void updateDr_Sub_shallReturnError_whenNoDCAELocationInSubProvided() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(null, USERNAME, USRPWD, "someFeedId", DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocationName", responseError.getFields()); + } + + @Test + public void updateDr_Sub_shallReturnError_whenFeedWithGivenIdInSubNotExists() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, "someFeedId", DELIVERY_URL, LOG_URL, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + @Test + public void updateDr_Sub_shallReturnSuccess_whenAddingNewSubscription() { + //given + String subId = "31"; + String feedId = assureFeedIsInDB(); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId, null, null, true); + Entity<DR_Sub> requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(200, resp.getStatus()); + + DR_Sub createdDrSub = resp.readEntity(DR_Sub.class); + assertNotNull(createdDrSub.getLastMod()); + assertEquals(subId, createdDrSub.getSubId()); + assertEquals(DCAE_LOCATION_NAME, createdDrSub.getDcaeLocationName()); + assertEquals(USERNAME, createdDrSub.getUsername()); + assertEquals(USRPWD, createdDrSub.getUserpwd()); + assertEquals(DELIVERY_URL_TEMPLATE + subId, createdDrSub.getDeliveryURL()); + assertEquals(LOG_URL_TEMPLATE + subId, createdDrSub.getLogURL()); + + assertSubscriptionExistInDB(createdDrSub); + } + + @Test + public void updateDr_Sub_shallReturnSuccess_whenUpdatingExistingSubscription() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub existingDrSub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + DR_Sub drSubUpdate = new DR_Sub("newDcaeLocationName", "newUserName", "newUserPwd", feedId, null, null, false); + Entity<DR_Sub> requestedEntity = Entity.entity(drSubUpdate, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(existingDrSub.getSubId()) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(200, resp.getStatus()); + + DR_Sub updatedDrSub = resp.readEntity(DR_Sub.class); + assertNotNull(updatedDrSub.getLastMod()); + assertEquals(existingDrSub.getSubId(), updatedDrSub.getSubId()); + assertEquals(drSubUpdate.getDcaeLocationName(), updatedDrSub.getDcaeLocationName()); + assertEquals(drSubUpdate.getUsername(), updatedDrSub.getUsername()); + assertEquals(drSubUpdate.getUserpwd(), updatedDrSub.getUserpwd()); + assertEquals(DELIVERY_URL_TEMPLATE + existingDrSub.getSubId(), updatedDrSub.getDeliveryURL()); + assertEquals(LOG_URL_TEMPLATE + existingDrSub.getSubId(), updatedDrSub.getLogURL()); + + assertSubscriptionExistInDB(updatedDrSub); + } + + @Test + public void deleteDr_Sub_shouldDeleteSubscriptionWithSuccess() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub dr_sub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_subs") + .path(dr_sub.getSubId()) + .request() + .delete(); + + //then + assertEquals("Shall delete subscription with success", 204, resp.getStatus()); + assertFalse("No entity object shall be returned",resp.hasEntity()); + assertSubscriptionNotExistInDB(dr_sub.getSubId()); + } + + @Test + public void deleteDr_Sub_shouldReturnErrorResponse_whenGivenSubIdNotFound() { + //given + String notExistingSubId = "6789"; + + //when + Response resp = testContainer.target("dr_subs") + .path(notExistingSubId) + .request() + .delete(); + + //then + assertEquals("Shall return error, when trying to delete not existing subscription", 404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + @Test + public void get_shallReturnExistingObject() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub dr_sub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_subs") + .path(dr_sub.getSubId()) + .request() + .get(); + + //ten + assertEquals("Subscription shall be found",200, resp.getStatus()); + assertEquals("Retrieved object shall be equal to eh one put into DB", dr_sub, resp.readEntity(DR_Sub.class)); + } + + @Test + public void get_shouldReturnError_whenSubWithIdNotFound() { + //given + String notExistingSubId = "1234"; + + //when + Response resp = testContainer.target("dr_subs") + .path(notExistingSubId) + .request() + .get(); + + //then + assertEquals("Subscription shall not be found", 404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + private DR_Sub addSub(String d, String un, String up, String feedId) { + DR_Sub dr_sub = new DR_Sub(d, un, up, feedId, + "https://subscriber.onap.org/foo", "https://dr-prov/sublog", true); + + Entity<DR_Sub> reqEntity2 = Entity.entity(dr_sub, MediaType.APPLICATION_JSON); + Response resp = testContainer.target("dr_subs").request().post(reqEntity2, Response.class); + System.out.println("POST dr_subs resp=" + resp.getStatus()); + assertEquals(201, resp.getStatus()); + dr_sub = resp.readEntity(DR_Sub.class); + + return dr_sub; + } + + private String assureFeedIsInDB() { + Feed feed = testFeedCreator.addFeed("SubscriberTestFeed", "feed for DR_Sub testing"); + assertNotNull("Feed shall be added into DB properly", feed); + return feed.getFeedId(); + } + + + private void assertSubscriptionNotExistInDB(String subId) { + assertEquals(404, testContainer.target("dr_subs") + .path(subId) + .request() + .get() + .getStatus()); + } + + private void assertSubscriptionExistInDB(DR_Sub sub) { + Response response = testContainer.target("dr_subs") + .path(sub.getSubId()) + .request() + .get(); + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertEquals(sub, response.readEntity(DR_Sub.class)); + } +} + + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DcaeLocationResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DcaeLocationResourceTest.java new file mode 100644 index 0000000..ff07927 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DcaeLocationResourceTest.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.server.ResourceConfig; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.Path; +import javax.ws.rs.GET; + + +public class DcaeLocationResourceTest extends JerseyTest { + + static DmaapObjectFactory factory = new DmaapObjectFactory(); + + @Override + protected Application configure() { + return new ResourceConfig( DcaeLocationResource.class ); + } + + private static final String fmt = "%24s: %s%n"; + + + +/* may conflict with test framework! + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } +*/ + + + + @Test + public void GetTest() { + Response resp = target( "dcaeLocations").request().get( Response.class ); + System.out.println( "GET feed resp=" + resp.getStatus() ); + + assertTrue( resp.getStatus() == 200 ); + } + @Test + public void PostTest() { + DcaeLocation loc = factory.genDcaeLocation( "central" ); + Entity<DcaeLocation> reqEntity = Entity.entity( loc, MediaType.APPLICATION_JSON ); + Response resp = target( "dcaeLocations").request().post( reqEntity, Response.class ); + System.out.println( "POST dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class ) ); + if ( resp.getStatus() != 409 ) { + assertTrue( resp.getStatus() == 201 ); + } + + resp = target( "dcaeLocations"). + path( loc.getDcaeLocationName()).request().get( Response.class ); + System.out.println( "GET feed resp=" + resp.getStatus() ); + + assertTrue( resp.getStatus() == 200 ); + } + + @Test + public void PutTest() { + DcaeLocation loc = factory.genDcaeLocation( "edge" ); + Entity<DcaeLocation> reqEntity = Entity.entity( loc, MediaType.APPLICATION_JSON ); + Response resp = target( "dcaeLocations").request().post( reqEntity, Response.class ); + System.out.println( "POST dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class ) ); + if ( resp.getStatus() != 409 ) { + assertTrue( resp.getStatus() == 201 ); + } + + + loc.setClli("ATLCTYNJ9999"); + reqEntity = Entity.entity( loc, MediaType.APPLICATION_JSON ); + resp = target( "dcaeLocations"). + path( loc.getDcaeLocationName()).request().put( reqEntity, Response.class ); + System.out.println( "PUT dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class ) ); + assertTrue( resp.getStatus() == 201 ); + + } + + @Test + public void DelTest() { + DcaeLocation loc = factory.genDcaeLocation( "edge" ); + Entity<DcaeLocation> reqEntity = Entity.entity( loc, MediaType.APPLICATION_JSON ); + Response resp = target( "dcaeLocations").request().post( reqEntity, Response.class ); + System.out.println( "POST dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class ) ); + if ( resp.getStatus() != 409 ) { + assertTrue( resp.getStatus() == 201 ); + } + + resp = target( "dcaeLocations"). + path( loc.getDcaeLocationName()).request().delete( Response.class ); + System.out.println( "DELETE dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class ) ); + assertTrue( resp.getStatus() == 204 ); + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DmaapResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DmaapResourceTest.java new file mode 100644 index 0000000..29ccb40 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/DmaapResourceTest.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; + +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + + +public class DmaapResourceTest extends JerseyTest { + + static DmaapObjectFactory factory = new DmaapObjectFactory(); + + @Override + protected Application configure() { + return new ResourceConfig( DmaapResource.class ); + //return new ResourceConfig( HelloResource.class ); + } + + private static final String fmt = "%24s: %s%n"; + + + +/* may conflict with test framework! + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } +*/ + + + + @Test + public void GetTest() { + Response resp = target( "dmaap").request().get( Response.class ); + assertTrue( resp.getStatus() == 200 ); + } + @Test + public void PostTest() { + + Dmaap dmaap = factory.genDmaap(); + Entity<Dmaap> reqEntity = Entity.entity( dmaap, MediaType.APPLICATION_JSON ); + Response resp = target( "dmaap").request().post( reqEntity, Response.class ); + System.out.println( resp.getStatus() ); + assertTrue( resp.getStatus() == 200 ); + } + + @Test + public void PutTest() { + + Dmaap dmaap = factory.genDmaap(); + Entity<Dmaap> reqEntity = Entity.entity( dmaap, MediaType.APPLICATION_JSON ); + + dmaap.setVersion( "2" ); + Response resp = target( "dmaap").request().put( reqEntity, Response.class ); + System.out.println( resp.getStatus() ); + assertTrue( resp.getStatus() == 200 ); + } + + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FastJerseyTestContainer.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FastJerseyTestContainer.java new file mode 100644 index 0000000..8d38a9f --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FastJerseyTestContainer.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import org.glassfish.jersey.test.JerseyTest; + +import javax.ws.rs.core.Application; + +class FastJerseyTestContainer extends JerseyTest { + + FastJerseyTestContainer(Application jaxrsApplication) { + super(jaxrsApplication); + } + + void init() throws Exception { + this.setUp(); + } + + void destroy() throws Exception { + this.tearDown(); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FeedResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FeedResourceTest.java new file mode 100644 index 0000000..89dca8a --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/FeedResourceTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.server.ResourceConfig; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.Path; +import javax.ws.rs.GET; + + +public class FeedResourceTest extends JerseyTest { + + @Override + protected Application configure() { + return new ResourceConfig( FeedResource.class ); + } + + private static final String fmt = "%24s: %s%n"; + + + +/* may conflict with test framework! + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } +*/ + + + + @Test + public void GetTest() { + Response resp = target( "feeds").request().get( Response.class ); + System.out.println( "GET feed resp=" + resp.getStatus() ); + + assertTrue( resp.getStatus() == 200 ); + } + @Test + public void PostTest() { + Feed feed = new Feed( "aPostTest", "1.0", "a unit test", "dgl", "unrestricted" ); + Entity<Feed> reqEntity = Entity.entity( feed, MediaType.APPLICATION_JSON ); + Response resp = target( "feeds").request().post( reqEntity, Response.class ); + System.out.println( "POST feed resp=" + resp.getStatus() ); + assertTrue( resp.getStatus() == 200 ); + } + +/* + @Test + public void PutTest() { + + Feed feed = new Feed( "aPutTest", "1.0", "a unit test", "dgl", "unrestricted" ); + Entity<Feed> reqEntity = Entity.entity( feed, MediaType.APPLICATION_JSON ); + Response resp = target( "feeds").request().post( reqEntity, Response.class ); + System.out.println( "POST feed resp=" + resp.getStatus() ); + String postResp = resp.readEntity( String.class ); + System.out.println( "postResp=" + postResp ); + Feed rFeed = new Feed( postResp ); getting a null pointer here + rFeed.setSuspended( true ); + String target = new String ("feeds/" + rFeed.getFeedId() ); + System.out.println( "PUT feed target=" + target ); + reqEntity = Entity.entity( rFeed, MediaType.APPLICATION_JSON ); + resp = target( target ).request().put( reqEntity, Response.class ); + System.out.println( "PUT feed resp=" + resp.getStatus() ); + assertTrue( resp.getStatus() == 200 ); + } +*/ + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/InfoResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/InfoResourceTest.java new file mode 100644 index 0000000..3f57f58 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/InfoResourceTest.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.server.ResourceConfig; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.Path; +import javax.ws.rs.GET; + + +public class InfoResourceTest extends JerseyTest { + + @Override + protected Application configure() { + return new ResourceConfig( InfoResource.class ); + } + + private static final String fmt = "%24s: %s%n"; + + + +/* may conflict with test framework! + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } +*/ + + + + @Test + public void GetTest() { + Response resp = target( "info").request().get( Response.class ); + assertTrue( resp.getStatus() == 204 ); + } + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClientResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClientResourceTest.java new file mode 100644 index 0000000..abe2e45 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClientResourceTest.java @@ -0,0 +1,304 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.resources; + +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.MR_Client; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class MR_ClientResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + private static FastJerseyTestContainer testContainer; + + @BeforeClass + public static void setUpClass() throws Exception { + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(MR_ClientResource.class).register(MR_ClusterResource.class).register(TopicResource.class)); + testContainer.init(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.getDmaap().remove(); + DatabaseClass.clearDatabase();*/ + } + + @Test + public void addMr_Client_shouldReturnErrorWhenNoFqtnProvided() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation", null, "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqtn", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldReturnErrorWhenNoLocationProvided() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client(null, "fqtn", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocationName", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldReturnErrorWhenNoClientRoleProvided() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation", "fqtn", null, new String[]{"GET"}), APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("clientRole or clientIdentity", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldReturnErrorWhenNoActionsProvided() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation", "fqtn", "clientRole", null), APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("action", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldReturnErrorWhereThereIsNoMrClusterAvailable() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocationName", "fqtn", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocationName", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldReturnErrorWhereThereIsNoTopicForFqtnAvailable() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation", "fqtn", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + createMrCluster(new MR_Cluster("dcaeLocation", "fqdn", "protocol", "port")); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(404, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqtn", responseError.getFields()); + } + + @Test + public void addMr_Client_shouldAddMrClient() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation2", "testTopic", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + createMrCluster(new MR_Cluster("dcaeLocation2", "fqdn", "protocol", "port")); + createTopic("testTopic"); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertMRClientExistInDB(response.readEntity(MR_Client.class)); + } + + @Test + public void deleteMr_Client_shouldDeleteMrClient() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation3", "testTopic", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + createMrCluster(new MR_Cluster("dcaeLocation3", "fqdn", "protocol", "port")); + createTopic("testTopic"); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + assertEquals(200, response.getStatus()); + + MR_Client mrClientEntity = response.readEntity(MR_Client.class); + Response deleteResponse = testContainer.target("mr_clients") + .path(mrClientEntity.getMrClientId()) + .request() + .delete(); + + assertEquals(204, deleteResponse.getStatus()); + assertMrClientNotExistInDB(mrClientEntity.getMrClientId()); + } + + @Test + public void deleteMr_Clients_shouldReturnMethodNotAllowedCodeWhenClientIdIsMissing() { + Response deleteResponse = testContainer.target("mr_clients") + .request() + .delete(); + + assertEquals(405, deleteResponse.getStatus()); + } + + @Test + public void getMr_Client_shouldReturnErrorWhenThereIsNoClient() { + Response response = testContainer.target("mr_clients") + .path("not_existing_id") + .request() + .get(); + + assertEquals(404, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("mrClientId", responseError.getFields()); + } + + @Test + public void updateMr_Client_shouldReturnErrorWhenNoFqtnProvided() { + MR_Client mrClient = new MR_Client("dcaeLocation", null, "clientRole", new String[]{"GET"}); + Entity<MR_Client> requestedEntity = entity(mrClient, APPLICATION_JSON); + + Response response = testContainer.target("mr_clients") + .path(mrClient.getMrClientId()) + .request() + .put(requestedEntity, Response.class); + + assertEquals(400, response.getStatus()); + ApiError responseError = response.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("fqtn", responseError.getFields()); + } + + @Test + public void updateMr_Client_shouldUpdate() { + Entity<MR_Client> requestedEntity = entity( + new MR_Client("dcaeLocation4", "testTopic", "clientRole", new String[]{"GET"}), APPLICATION_JSON); + + createMrCluster(new MR_Cluster("dcaeLocation4", "fqdn", "protocol", "port")); + createTopic("testTopic"); + + Response response = testContainer.target("mr_clients") + .request() + .post(requestedEntity, Response.class); + MR_Client createdMrClient = response.readEntity(MR_Client.class); + createdMrClient.setDcaeLocationName("updatedDcaeLocation"); + + + Response updateResponse = testContainer.target("mr_clients") + .path(createdMrClient.getMrClientId()) + .request() + .put(requestedEntity, Response.class); + + assertEquals(200, updateResponse.getStatus()); + assertTrue(updateResponse.hasEntity()); + assertMRClientExistInDB(updateResponse.readEntity(MR_Client.class)); + + } + + @Test + public void getMr_Clients_test() { + Response response = testContainer.target("mr_clients").request().get(Response.class); + System.out.println("GET dr_subs response=" + response.getStatus()); + + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + } + + + private void createMrCluster(MR_Cluster cluster) { + Response response = testContainer.target("mr_clusters") + .request() + .post(entity(cluster, APPLICATION_JSON), Response.class); + assertEquals(201, response.getStatus()); + } + + private void createTopic(String tname) { + Topic topic = new Topic(); + topic.setFqtn(tname); + topic.setFqtn(tname); + DatabaseClass.getTopics().put(topic.getFqtn(), topic); + } + + private void assertMRClientExistInDB(MR_Client created) { + Response response = testContainer.target("mr_clients") + .path(created.getMrClientId()) + .request() + .get(); + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + MR_Client receivedMrClient = response.readEntity(MR_Client.class); + assertEquals(created.getFqtn(), receivedMrClient.getFqtn()); + assertEquals(created.getDcaeLocationName(), receivedMrClient.getDcaeLocationName()); + } + + private void assertMrClientNotExistInDB(String clientId) { + assertEquals(404, testContainer.target("mr_clients") + .path(clientId) + .request() + .get() + .getStatus()); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java new file mode 100644 index 0000000..9027f13 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java @@ -0,0 +1,284 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import static javax.ws.rs.client.Entity.entity; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import org.eclipse.jetty.http.HttpStatus; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +public class MR_ClusterResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + private static FastJerseyTestContainer testContainer; + private static final String MR_CLUSTERS_TARGET = "mr_clusters"; + + @BeforeClass + public static void setUpClass() throws Exception { + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(MR_ClusterResource.class).register(DcaeLocationResource.class)); + testContainer.init(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.getDmaap().remove(); + DatabaseClass.clearDatabase();*/ + } + + @Before + public void setUpClusterAndLocation() { + DatabaseClass.clearDatabase(); + } + + @Test + public void getMrClusters_shouldReturnEmptyList_whenNoMrClustersInDataBase() { + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).request().get(Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + + List<MR_Cluster> mrClusters = resp.readEntity(new GenericType<List<MR_Cluster>>() { + }); + assertTrue(mrClusters.isEmpty()); + } + + @Test + public void addMrCluster_shouldReturnValidationError_whenDcaeLocationNameNotProvided() { + //given + Entity<MR_Cluster> requestEntity = entity(new MR_Cluster(), APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).request().post(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("dcaeLocationName", errorObj.getFields()); + } + + @Test + public void addMrCluster_shouldReturnValidationError_whenFqdnNotProvided() { + //given + MR_Cluster mr_cluster = new MR_Cluster(); + mr_cluster.setDcaeLocationName("central-cloud"); + Entity<MR_Cluster> requestEntity = entity(mr_cluster, APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).request().post(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("fqdn", errorObj.getFields()); + } + + @Test + public void addMrCluster_shouldAddMrClusterToDatabase() { + //given + MR_Cluster mrCluster = DMAAP_OBJECT_FACTORY.genMR_Cluster("edge"); + Entity<MR_Cluster> requestEntity = entity(mrCluster, APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).request().post(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + MR_Cluster respEntity = resp.readEntity(MR_Cluster.class); + assertTrue(respEntity.isStatusValid()); + } + + @Test + public void addMrCluster_shouldReturnInvalidMrCluster_whenClusterCannotBeAddedToDatabase() { + //given + MR_Cluster mrCluster = DMAAP_OBJECT_FACTORY.genMR_Cluster("central"); + Entity<MR_Cluster> requestEntity = entity(mrCluster, APPLICATION_JSON); + prepareDcaeLocationForCentralCluster(); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).request().post(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + MR_Cluster respEntity = resp.readEntity(MR_Cluster.class); + assertFalse(respEntity.isStatusValid()); + } + + private void prepareDcaeLocationForCentralCluster() { + DcaeLocation centralDcaeLoc = DMAAP_OBJECT_FACTORY.genDcaeLocation("central"); + centralDcaeLoc.setStatus(DmaapObject_Status.VALID); + DatabaseClass.getDcaeLocations().put(centralDcaeLoc.getDcaeLocationName(), centralDcaeLoc); + } + + @Test + public void updateMrCluster_shouldReturnValidationError_whenDcaeLocationNameNotProvided() { + //given + Entity<MR_Cluster> requestEntity = entity(new MR_Cluster(), APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path("clusterId") + .request().put(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("dcaeLocationName", errorObj.getFields()); + } + + @Test + public void updateMrCluster_shouldReturnApiError_whenMrClusterWithGivenIdNotFound() { + //given + MR_Cluster mr_cluster = new MR_Cluster(); + mr_cluster.setDcaeLocationName("central-cloud"); + Entity<MR_Cluster> requestEntity = entity(mr_cluster, APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path("notExistingMrCluster") + .request().put(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.NOT_FOUND_404, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("dcaeLocationName", errorObj.getFields()); + } + + @Test + public void updateMrCluster_shouldUpdateClusterInDatabase() { + //given + String newReplicationGroup = "someNewReplicationGroup"; + prepareDcaeLocationForEdgeCluster(); + String clusterId = provideExistingEdgeMRClusterId(); + MR_Cluster changedMrCluster = DMAAP_OBJECT_FACTORY.genMR_Cluster("edge"); + changedMrCluster.setReplicationGroup(newReplicationGroup); + Entity<MR_Cluster> requestEntity = entity(changedMrCluster, APPLICATION_JSON); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path(clusterId) + .request().put(requestEntity, Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + MR_Cluster respEntity = resp.readEntity(MR_Cluster.class); + assertTrue(respEntity.isStatusValid()); + assertEquals(newReplicationGroup, respEntity.getReplicationGroup()); + } + + private void prepareDcaeLocationForEdgeCluster() { + DcaeLocation edgeDcaeLoc = DMAAP_OBJECT_FACTORY.genDcaeLocation("edge"); + edgeDcaeLoc.setStatus(DmaapObject_Status.VALID); + DatabaseClass.getDcaeLocations().put(edgeDcaeLoc.getDcaeLocationName(), edgeDcaeLoc); + } + + private String provideExistingEdgeMRClusterId() { + MR_Cluster cluster = DMAAP_OBJECT_FACTORY.genMR_Cluster("edge"); + cluster.setStatus(DmaapObject_Status.VALID); + DatabaseClass.getMr_clusters().put(cluster.getDcaeLocationName(), cluster); + return cluster.getDcaeLocationName(); + } + + @Test + public void deleteMr_Cluster_shouldReturnApiError_whenTryingToDeleteNotExistingMrCluster() { + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path("notExistingClusterId") + .request().delete(Response.class); + + //then + assertEquals(HttpStatus.NOT_FOUND_404, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("dcaeLocationName", errorObj.getFields()); + } + + @Test + public void deleteMr_Cluster_shouldRemoveMrClusterFromDatabase() { + //given + String clusterId = provideExistingEdgeMRClusterId(); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path(clusterId) + .request().delete(Response.class); + + //then + assertEquals(HttpStatus.NO_CONTENT_204, resp.getStatus()); + assertFalse(resp.hasEntity()); + } + + @Test + public void getMr_Cluster_shouldReturnApiError_whenTryingToGetNotExistingMrCluster() { + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path("notExistingClusterId") + .request().get(Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("dcaeLocationName", errorObj.getFields()); + } + + @Test + public void getMr_Cluster_shouldReturnExistingMrCluster() { + //given + String clusterId = provideExistingEdgeMRClusterId(); + + //when + Response resp = testContainer.target(MR_CLUSTERS_TARGET).path(clusterId) + .request().get(Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + MR_Cluster mrCluster = resp.readEntity(MR_Cluster.class); + assertEquals(clusterId, mrCluster.getDcaeLocationName()); + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequestTimeLogFilterTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequestTimeLogFilterTest.java new file mode 100644 index 0000000..0c88c0c --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequestTimeLogFilterTest.java @@ -0,0 +1,78 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dmaap
+ * ================================================================================
+ * Copyright (C) 2019 Nokia 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.dbcapi.resources;
+
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import com.att.eelf.configuration.EELFLogger;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class RequestTimeLogFilterTest {
+
+ private Clock clock ;
+ private RequestTimeLogFilter requestTimeLogFilter;
+ public static final long START = 1L;
+ @Mock
+ private ContainerRequestContext requestContext;
+ @Mock
+ private ContainerResponseContext responseContext;
+ @Mock
+ private EELFLogger logger;
+
+
+ @Before
+ public void setup() {
+ clock = Clock.fixed(Instant.parse("1970-01-01T00:00:10Z"), ZoneId.systemDefault());
+ requestTimeLogFilter = new RequestTimeLogFilter(logger, clock);
+ }
+
+ @Test
+ public void shouldHaveDefaultConstructor() {
+ assertNotNull(new RequestTimeLogFilter());
+ }
+
+ @Test
+ public void filterShouldSetStartTimestampProperty() {
+ requestTimeLogFilter.filter(requestContext);
+ verify(requestContext).setProperty("start",clock.millis());
+ }
+
+ @Test
+ public void filterShouldPrintElapsedTime() {
+ when(requestContext.getProperty("start")).thenReturn(START);
+
+ requestTimeLogFilter.filter(requestContext, responseContext);
+
+ verify(logger).info(anyString(),eq(clock.millis() - START));
+ }
+}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java new file mode 100644 index 0000000..f07058b --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredCheckerTest.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 NOKIA 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.dbcapi.resources; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.dmaap.dbcapi.model.ApiError; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.junit.Assert.fail; + +public class RequiredCheckerTest { + + private static final String NAME = "field_name"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + private RequiredChecker requiredChecker = new RequiredChecker(); + + + @Test + public void required_shouldThrowExceptionWhenObjectIsNull() throws RequiredFieldException { + thrown.expect(RequiredFieldException.class); + thrown.expect(new ApiErrorMatcher(new ApiError(BAD_REQUEST.getStatusCode(), + "missing required field", NAME))); + + requiredChecker.required(NAME, null); + } + + @Test + public void required_shouldThrowExceptionWhenRegexValidationFailed() throws RequiredFieldException { + thrown.expect(RequiredFieldException.class); + thrown.expect(new ApiErrorMatcher(new ApiError(BAD_REQUEST.getStatusCode(), + "value 'with white space' violates regexp check '^\\S+$'", NAME))); + + requiredChecker.required(NAME, "with white space", "^\\S+$"); + } + + @Test + public void required_shouldPassValidation() { + try { + requiredChecker.required(NAME, "value", "^\\S+$"); + } catch (RequiredFieldException e) { + fail("No exception should be thrown"); + } + } + + class ApiErrorMatcher extends BaseMatcher { + + private final ApiError expectedApiEror; + + ApiErrorMatcher(ApiError expectedApiEror) { + this.expectedApiEror = expectedApiEror; + } + + @Override + public boolean matches(Object exception) { + return expectedApiEror.equals(((RequiredFieldException) exception).getApiError()); + } + + @Override + public void describeTo(Description description) { + description.appendText("Following ApiError is expected: ").appendValue(expectedApiEror); + } + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredFieldExceptionTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredFieldExceptionTest.java new file mode 100644 index 0000000..d3dcc42 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/RequiredFieldExceptionTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 IBM + * =================================================================== + * 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.dbcapi.resources; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; + +public class RequiredFieldExceptionTest { + ApiError apiError; + RequiredFieldException requiredFieldException; + String expectedValue; + + @Before + public void setUp() { + apiError = new ApiError(BAD_REQUEST.getStatusCode(), "value 'with white space' violates regexp check '^\\S+$'", + "field_name"); + + expectedValue = "RequiredFieldException{" + "apiError=" + apiError + '}'; + + requiredFieldException = new RequiredFieldException(apiError); + } + + @Test + public void testRequiredFieldExceptionToString() { + assertEquals(expectedValue, requiredFieldException.toString()); + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/ResponseBuilderTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/ResponseBuilderTest.java new file mode 100644 index 0000000..ff61d14 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/ResponseBuilderTest.java @@ -0,0 +1,96 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 NOKIA 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.dbcapi.resources; + +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; + +import javax.ws.rs.core.Response; + +import static javax.ws.rs.core.Response.Status.NOT_FOUND; +import static javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE; +import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; +import static org.junit.Assert.assertEquals; + +public class ResponseBuilderTest { + + private static final String OBJECT = "Objcect"; + private static final String MESSAGE = "msg"; + private static final int CODE = 100; + private ResponseBuilder responseBuilder = new ResponseBuilder(); + + @Test + public void success_shouldCreateResponseWithOKStatusCode() { + + Response response = responseBuilder.success(OBJECT); + + assertEquals(OBJECT, response.getEntity()); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void success_shouldCreateResponseWithDefinedStatusCode() { + + Response response = responseBuilder.success(CODE, OBJECT); + + assertEquals(OBJECT, response.getEntity()); + assertEquals(CODE, response.getStatus()); + } + + @Test + public void unauthorized_shouldCreateCorrectResponse() { + + ApiError error = new ApiError(UNAUTHORIZED.getStatusCode(), MESSAGE, "Authorization"); + Response response = responseBuilder.unauthorized(MESSAGE); + + assertEquals(error, response.getEntity()); + assertEquals(error.getCode(), response.getStatus()); + } + + @Test + public void unavailable_shouldCreateCorrectResponse() { + + ApiError error = new ApiError(SERVICE_UNAVAILABLE.getStatusCode(), + "Request is unavailable due to unexpected condition"); + Response response = responseBuilder.unavailable(); + + assertEquals(error, response.getEntity()); + assertEquals(error.getCode(), response.getStatus()); + } + + @Test + public void notFound_shouldCreateCorrectResponse() { + ApiError error = new ApiError(NOT_FOUND.getStatusCode(), "Requested object not found"); + Response response = responseBuilder.notFound(); + + assertEquals(error, response.getEntity()); + assertEquals(error.getCode(), response.getStatus()); + } + + @Test + public void error_shouldCreateCorrectResponse() { + ApiError error = new ApiError(CODE, "Some Error"); + Response response = responseBuilder.error(error); + + assertEquals(error, response.getEntity()); + assertEquals(error.getCode(), response.getStatus()); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TestFeedCreator.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TestFeedCreator.java new file mode 100644 index 0000000..e4dedb1 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TestFeedCreator.java @@ -0,0 +1,49 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * org.onap.dmaap
+ * ================================================================================
+ * Copyright (C) 2019 Nokia 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.dbcapi.resources;
+
+import static org.junit.Assert.assertTrue;
+
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.dmaap.dbcapi.model.Feed;
+
+
+public class TestFeedCreator {
+
+
+ private final FastJerseyTestContainer testContainer;
+
+ public TestFeedCreator(FastJerseyTestContainer testContainer) {
+ this.testContainer = testContainer;
+ }
+
+ Feed addFeed(String name, String desc) {
+ Feed feed = new Feed(name, "1.0", desc, "dgl", "unrestricted");
+ Entity<Feed> reqEntity = Entity.entity(feed, MediaType.APPLICATION_JSON);
+ Response resp = testContainer.target("feeds").request().post(reqEntity, Response.class);
+ int rc = resp.getStatus();
+ System.out.println("POST feed resp=" + rc);
+ assertTrue(rc == 200 || rc == 409);
+ feed = resp.readEntity(Feed.class);
+ return feed;
+ }
+}
diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java new file mode 100644 index 0000000..5b7c46d --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +import java.util.List; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.eclipse.jetty.http.HttpStatus; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status; +import org.onap.dmaap.dbcapi.model.FqtnType; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.model.ReplicationType; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; + +public class TopicResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + private static final String TOPICS_TARGET = "topics"; + + private static FastJerseyTestContainer testContainer; + + @BeforeClass + public static void setUpClass() throws Exception { + //TODO: init is still needed here to assure that dmaap is not null + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTestContainer(new ResourceConfig() + .register(TopicResource.class)); + testContainer.init(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + } + + @Before + public void setUpClusterAndLocation() { + DatabaseClass.clearDatabase(); + + DcaeLocation centralDcaeLoc = DMAAP_OBJECT_FACTORY.genDcaeLocation("central"); + centralDcaeLoc.setStatus(DmaapObject_Status.VALID); + DatabaseClass.getDcaeLocations().put(centralDcaeLoc.getDcaeLocationName(), centralDcaeLoc); + + MR_Cluster cluster = DMAAP_OBJECT_FACTORY.genMR_Cluster("central"); + cluster.setStatus(DmaapObject_Status.VALID); + DatabaseClass.getMr_clusters().put(cluster.getDcaeLocationName(), cluster); + } + + @Test + public void getTopics_shouldReturnEmptyList_whenNoTopicsInDataBase() { + //when + Response resp = testContainer.target(TOPICS_TARGET).request().get(Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + + List<Topic> topics = resp.readEntity(new GenericType<List<Topic>>() { + }); + assertTrue(topics.isEmpty()); + } + + @Test + public void getTopics_shouldReturnTopicsRegisteredInDataBase() { + //given + Topic topic1 = DMAAP_OBJECT_FACTORY.genSimpleTopic("testTopic1"); + Topic topic2 = DMAAP_OBJECT_FACTORY.genSimpleTopic("testTopic2"); + DatabaseClass.getTopics().put(topic1.getFqtn(), topic1); + DatabaseClass.getTopics().put(topic2.getFqtn(), topic2); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().get(Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + + List<Topic> topics = resp.readEntity(new GenericType<List<Topic>>() { + }); + assertEquals(2, topics.size()); + assertTrue(topics.contains(topic1)); + assertTrue(topics.contains(topic2)); + } + + @Test + public void getTopics_shouldReturnValidationError_whenTopicNameIsInvalid() { + //given + String topicName = "wrong Topic Name"; + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topicName).request().get(Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("topicName", errorObj.getFields()); + } + + @Test + public void getTopic_shouldReturnError_whenRequestedTopicNotFound() { + //given + String topicName = "notExistingTopic"; + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topicName).request().get(Response.class); + + //then + assertEquals(HttpStatus.NOT_FOUND_404, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("fqtn", errorObj.getFields()); + } + + @Test + public void getTopic_shouldReturnTopicInformation_whenRequestedTopicExists() { + //given + Topic topic1 = DMAAP_OBJECT_FACTORY.genSimpleTopic("testTopic1"); + DatabaseClass.getTopics().put(topic1.getFqtn(), topic1); + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topic1.getFqtn()).request().get(Response.class); + + //then + assertEquals(HttpStatus.OK_200, resp.getStatus()); + assertTrue(resp.hasEntity()); + Topic retrievedTopic = resp.readEntity(Topic.class); + assertEquals(topic1, retrievedTopic); + } + + + @Test + public void deleteTopic_shouldReturnError_whenTopicNotFound() { + //given + String topicName = "notExisting"; + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topicName).request().delete(Response.class); + + //then + assertEquals(HttpStatus.NOT_FOUND_404, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("fqtn", errorObj.getFields()); + } + + @Test + public void deleteTopic_shouldDeleteTopicFromDataBase_whenFound() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("testTopic"); + DatabaseClass.getTopics().put(topic.getFqtn(), topic); + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topic.getFqtn()).request().delete(Response.class); + + //then + assertEquals(HttpStatus.NO_CONTENT_204, resp.getStatus()); + assertFalse(resp.hasEntity()); + } + + @Test + public void addTopic_shouldReturnValidationError_whenTopicNameIsInvalid() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("wrong topic name with spaces"); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("topicName", errorObj.getFields()); + } + + @Test + public void addTopic_shouldReturnValidationError_whenTopicDescriptionNotProvided() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + topic.setTopicDescription(null); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("topicDescription", errorObj.getFields()); + } + + @Test + public void addTopic_shouldReturnValidationError_whenTopicOwnerNotProvided() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + topic.setOwner(null); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("owner", errorObj.getFields()); + } + + @Test + public void addTopic_shouldReturnError_whenTopicAlreadyExist() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + DatabaseClass.getTopics().put(topic.getFqtn(), topic); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.CONFLICT_409, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("fqtn", errorObj.getFields()); + } + + @Test + public void addTopic_shouldReturnExistingTopic_whenTopicAlreadyExist_andUseExistingQueryParamUsed() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + DatabaseClass.getTopics().put(topic.getFqtn(), topic); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).queryParam("useExisting", true).request() + .post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + assertEquals(topic, resp.readEntity(Topic.class)); + } + + @Test + public void addTopic_shouldReturnError_whenAddingTopicWithInvalidGlobalMRclusterHostname() { + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + topic.setReplicationCase(ReplicationType.REPLICATION_CENTRAL_TO_GLOBAL); + topic.setGlobalMrURL("some.invalid.Glob$al.M@R.ur)l"); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals("globalMrURL", errorObj.getFields()); + } + + @Test + public void addTopic_shouldAddTopicWithDefaultOptionalValues_whenNotProvided() { + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + Topic createdTopic = resp.readEntity(Topic.class); + assertEquals(topic, createdTopic); + assertEquals(FqtnType.FQTN_LEGACY_FORMAT, createdTopic.getFqtnStyle()); + assertEquals("2", createdTopic.getPartitionCount()); + assertEquals("1", createdTopic.getReplicationCount()); + } + + @Test + public void addTopic_shouldAddTopicWithOriginalOptionalValues_whenProvided() { + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + topic.setFqtnStyle(FqtnType.FQTN_PROJECTID_FORMAT); + topic.setFqtn(topic.genFqtn()); + topic.setPartitionCount("6"); + topic.setReplicationCount("9"); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).request().post(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.CREATED_201, resp.getStatus()); + assertTrue(resp.hasEntity()); + Topic createdTopic = resp.readEntity(Topic.class); + assertEquals(topic, createdTopic); + assertEquals(FqtnType.FQTN_PROJECTID_FORMAT, createdTopic.getFqtnStyle()); + assertEquals("6", createdTopic.getPartitionCount()); + assertEquals("9", createdTopic.getReplicationCount()); + } + + @Test + public void updateTopic_shouldReturnError_withInformationThatItIsNotSupported() { + //given + Topic topic = DMAAP_OBJECT_FACTORY.genSimpleTopic("topicName"); + DatabaseClass.getTopics().put(topic.getFqtn(), topic); + topic.setOwner("newOwner"); + Entity<Topic> requestedEntity = Entity.entity(topic, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target(TOPICS_TARGET).path(topic.getFqtn()).request() + .put(requestedEntity, Response.class); + + //then + assertEquals(HttpStatus.BAD_REQUEST_400, resp.getStatus()); + assertTrue(resp.hasEntity()); + ApiError errorObj = resp.readEntity(ApiError.class); + assertEquals(TopicResource.UNSUPPORTED_PUT_MSG, errorObj.getMessage()); + } + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/JettyServerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/JettyServerTest.java new file mode 100644 index 0000000..35c9243 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/JettyServerTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.server; + +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; +import org.onap.dmaap.dbcapi.util.DmaapConfig; +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.Properties; + +public class JettyServerTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + JettyServer m = null; + + @Before + public void setUp() throws Exception { + Properties p = DmaapConfig.getConfig(); + try { + m = new JettyServer(p); + } catch (Exception e ) { + } + } + + @After + public void tearDown() throws Exception { + try { + m.getServer().stop(); + } catch (Exception e ) { + } + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.server.JettyServer", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.server.JettyServer", "set", v ); + + } + + @Test + public void test3() { + } + + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/MainTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/MainTest.java new file mode 100644 index 0000000..0e74f45 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/server/MainTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.server; + +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class MainTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + Main m; + + + @Before + public void setUp() throws Exception { + //m = new Main(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.server.Main", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.server.Main", "set", v ); + + } + +/* + @Test + public void test3() { + String[] args = { "--help", "--version" }; + + try { + m.main( args ); + } catch (Exception e ) { + } + + } +*/ + + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafPermissionServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafPermissionServiceTest.java new file mode 100644 index 0000000..716736e --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafPermissionServiceTest.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.service; + +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.dmaap.dbcapi.aaf.AafService; +import org.onap.dmaap.dbcapi.aaf.AafUserRole; +import org.onap.dmaap.dbcapi.aaf.DmaapGrant; +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.MR_Client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status.INVALID; +import static org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status.VALID; + +@RunWith(JUnitParamsRunner.class) +public class AafPermissionServiceTest { + + private static final String ROLE = "dmaap.mr.demoTopic.publisher"; + private static final String IDENTITY = "dmaap-bc@dmaap-bc.onap.org"; + private static final String TOPIC_PERM = "org.onap.dmaap.mr.topic"; + private static final String FQTN = "org.onap.dmaap.mr.demoTopic"; + private static final String PUB_ACTION = "pub"; + private static final int INTERNAL_SERVER_ERROR = 500; + @Mock + private AafService aafService; + @Mock + private DmaapService dmaapService; + @Mock + private MR_Client mrClient; + private AafPermissionService aafPermissionService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + aafPermissionService = new AafPermissionService(aafService, dmaapService); + given(mrClient.getClientIdentity()).willReturn(IDENTITY); + given(mrClient.getFqtn()).willReturn(FQTN); + given(mrClient.getAction()).willReturn(new String[]{PUB_ACTION}); + given(dmaapService.getTopicPerm()).willReturn(TOPIC_PERM); + } + + @Test + @Parameters({"201", "409"}) + public void shouldAssignClientToRole(int aafServiceReturnedCode) { + AafUserRole userRole = new AafUserRole(IDENTITY, ROLE); + given(aafService.addUserRole(userRole)).willReturn(aafServiceReturnedCode); + + ApiError apiError = aafPermissionService.assignClientToRole(mrClient, ROLE); + + then(aafService).should().addUserRole(userRole); + then(mrClient).should().setStatus(VALID); + assertOkStatus(apiError); + } + + @Test + public void shouldReturnErrorStatusWhenClientWasNotAssignedToRole() { + AafUserRole userRole = new AafUserRole(IDENTITY, ROLE); + given(aafService.addUserRole(userRole)).willReturn(INTERNAL_SERVER_ERROR); + + ApiError apiError = aafPermissionService.assignClientToRole(mrClient, ROLE); + + then(mrClient).should().setStatus(INVALID); + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + @Parameters({"201", "409"}) + public void shouldGrantActionPermissionForClientRole(int aafServiceReturnedCode) { + DmaapGrant grant = new DmaapGrant(new DmaapPerm(TOPIC_PERM, ":topic." + FQTN, PUB_ACTION), ROLE); + given(mrClient.getClientRole()).willReturn(ROLE); + given(aafService.addGrant(grant)).willReturn(aafServiceReturnedCode); + + ApiError apiError = aafPermissionService.grantClientRolePerms(mrClient); + + then(aafService).should().addGrant(grant); + then(mrClient).should().setStatus(VALID); + assertOkStatus(apiError); + } + + @Test + public void shouldReturnErrorStatusWhenPermissionWasNotGrantToRole() { + DmaapGrant grant = new DmaapGrant(new DmaapPerm(TOPIC_PERM, ":topic." + FQTN, PUB_ACTION), ROLE); + given(mrClient.getClientRole()).willReturn(ROLE); + given(aafService.addGrant(grant)).willReturn(INTERNAL_SERVER_ERROR); + + ApiError apiError = aafPermissionService.grantClientRolePerms(mrClient); + + then(mrClient).should().setStatus(INVALID); + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldReturnOkStatusWhenClientRoleIsNull() { + given(mrClient.getClientRole()).willReturn(null); + + ApiError apiError = aafPermissionService.grantClientRolePerms(mrClient); + + verifyZeroInteractions(aafService); + then(mrClient).should().setStatus(VALID); + assertOkStatus(apiError); + } + + private void assertErrorStatus(ApiError apiError, int code) { + assertEquals(code, apiError.getCode()); + } + + private void assertOkStatus(ApiError apiError) { + assertTrue(apiError.is2xx()); + assertEquals("OK", apiError.getMessage()); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafTopicSetupServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafTopicSetupServiceTest.java new file mode 100644 index 0000000..0ca406a --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/AafTopicSetupServiceTest.java @@ -0,0 +1,470 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.service; + +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.dmaap.dbcapi.aaf.AafNamespace; +import org.onap.dmaap.dbcapi.aaf.AafRole; +import org.onap.dmaap.dbcapi.aaf.AafService; +import org.onap.dmaap.dbcapi.aaf.AafUserRole; +import org.onap.dmaap.dbcapi.aaf.DmaapGrant; +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +import java.util.List; + +import static com.google.common.collect.Lists.newArrayList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; + +@RunWith(JUnitParamsRunner.class) +public class AafTopicSetupServiceTest { + + private static final int INTERNAL_SERVER_ERROR = 500; + private static final int NOT_FOUND = 404; + private static final int CREATED = 201; + private static final int OK = 200; + private static final String TOPIC_NS_ROOT = "org.onap.dmaap.mr"; + private static final String TOPIC_PERM = "org.onap.dmaap.mr.topic"; + private static final String TOPIC_FQTN = "org.onap.dmaap.mr.sample_topic"; + private static final String IDENTITY = "dmaap-bc@dmaap-bc.onap.org"; + private AafServiceStub aafService = new AafServiceStub(); + @Mock + private DmaapService dmaapService; + @Mock + private DmaapConfig dmaapConfig; + private AafTopicSetupService aafTopicSetupService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + Dmaap dmaap = new Dmaap(); + dmaap.setTopicNsRoot(TOPIC_NS_ROOT); + given(dmaapService.getDmaap()).willReturn(dmaap); + given(dmaapService.getTopicPerm()).willReturn(TOPIC_PERM); + given(dmaapConfig.getProperty("aaf.CreateTopicRoles", "true")).willReturn("true"); + given(dmaapConfig.getProperty("MR.ClientDeleteLevel", "0")).willReturn("2"); + aafTopicSetupService = new AafTopicSetupService(aafService, dmaapService, dmaapConfig); + } + + @Test + @Parameters({"201", "409"}) + public void shouldCreatePublisherSubscriberViewerPermissions(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + + aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "pub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "sub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view")); + } + + @Test + public void shouldReturnOkStatusWhenNoError() { + aafService.givenReturnCode(201); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertOkStatus(apiError); + } + + @Test + @Parameters({"201", "409"}) + public void shouldAddNamespace(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + Topic topic = givenTopic(TOPIC_FQTN); + + aafTopicSetupService.aafTopicSetup(topic); + + AafNamespace namespace = new AafNamespace(TOPIC_FQTN, IDENTITY); + aafService.shouldAddNamespace(namespace); + } + + @Test + @Parameters({"201", "409"}) + public void shouldCretePublisherRoleAndSetItToTopic(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + Topic topic = givenTopic(TOPIC_FQTN); + + aafTopicSetupService.aafTopicSetup(topic); + + AafRole role = new AafRole(TOPIC_FQTN, "publisher"); + aafService.shouldAddRole(role); + assertEquals(role.getFullyQualifiedRole(), topic.getPublisherRole()); + } + + @Test + @Parameters({"201", "409"}) + public void shouldCreteSubscriberRoleAndSetItToTopic(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + Topic topic = givenTopic(TOPIC_FQTN); + + aafTopicSetupService.aafTopicSetup(topic); + + AafRole role = new AafRole(TOPIC_FQTN, "subscriber"); + aafService.shouldAddRole(role); + assertEquals(role.getFullyQualifiedRole(), topic.getSubscriberRole()); + } + + @Test + @Parameters({"201", "409"}) + public void shouldGrantPubAndViewPermissionToPublisherRole(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + + aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + AafRole role = new AafRole(TOPIC_FQTN, "publisher"); + DmaapPerm pubPerm = new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "pub"); + DmaapPerm viewPerm = new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view"); + aafService.shouldAddGrant(new DmaapGrant(pubPerm, role.getFullyQualifiedRole())); + aafService.shouldAddGrant(new DmaapGrant(viewPerm, role.getFullyQualifiedRole())); + } + + @Test + @Parameters({"201", "409"}) + public void shouldGrantSubAndViewPermissionToSubscriberRole(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + + aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + AafRole role = new AafRole(TOPIC_FQTN, "subscriber"); + DmaapPerm subPerm = new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "sub"); + DmaapPerm viewPerm = new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view"); + aafService.shouldAddGrant(new DmaapGrant(subPerm, role.getFullyQualifiedRole())); + aafService.shouldAddGrant(new DmaapGrant(viewPerm, role.getFullyQualifiedRole())); + } + + @Test + public void shouldCreateOnlyPermissionsWhenCreateTopicRolesIsFalse() { + given(dmaapConfig.getProperty("aaf.CreateTopicRoles", "true")).willReturn("false"); + + aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "pub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "sub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view")); + aafService.shouldHaveNoNamespaceRolesAndGrantsAdded(); + } + + @Test + public void shouldCreateOnlyPermissionsWhenTopicFqtnDoesntStartWithNsRoot() { + + String topicFqtn = "sample_topic"; + aafTopicSetupService.aafTopicSetup(givenTopic(topicFqtn)); + + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "pub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "sub")); + aafService.shouldAddPerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "view")); + aafService.shouldHaveNoNamespaceRolesAndGrantsAdded(); + } + + @Test + public void shouldHandleExceptionWhenTopicSnRootIsNotDefined() { + Dmaap dmaap = new Dmaap(); + dmaap.setTopicNsRoot(null); + given(dmaapService.getDmaap()).willReturn(dmaap); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldHandleExceptionWhenPermissionCreationWasFailed() { + aafService.givenAddPermStatus(NOT_FOUND); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldHandleExceptionWhenNamespaceCreationWasFailed() { + aafService.givenAddNamespaceStatus(NOT_FOUND); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldHandleExceptionWhenRoleCreationWasFailed() { + aafService.givenAddRoleStatus(NOT_FOUND); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldHandleExceptionWhenGrantPermToRoleWasFailed() { + aafService.givenAddGrantStatus(NOT_FOUND); + + ApiError apiError = aafTopicSetupService.aafTopicSetup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, NOT_FOUND); + } + + @Test + @Parameters({"200", "404"}) + public void shouldremovePublisherSubscriberViewerPermissions(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + + aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "pub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "sub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view")); + } + + @Test + @Parameters({"200", "404"}) + public void shouldRemoveNamespace(int aafServiceReturnedCode) { + aafService.givenReturnCode(aafServiceReturnedCode); + Topic topic = givenTopic(TOPIC_FQTN); + + aafTopicSetupService.aafTopicCleanup(topic); + + AafNamespace namespace = new AafNamespace(TOPIC_FQTN, IDENTITY); + aafService.shouldRemoveNamespace(namespace); + } + + @Test + public void shouldRemoveOnlyPermissionsWhenCreateTopicRolesIsFalse() { + given(dmaapConfig.getProperty("aaf.CreateTopicRoles", "true")).willReturn("false"); + + aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "pub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "sub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + TOPIC_FQTN, "view")); + aafService.shouldNotRemoveNamespace(); + } + + @Test + public void shouldRemoveOnlyPermissionsWhenTopicFqtnDoesntStartWithNsRoot() { + + String topicFqtn = "sample_topic"; + aafTopicSetupService.aafTopicCleanup(givenTopic(topicFqtn)); + + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "pub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "sub")); + aafService.shouldRemovePerm(new DmaapPerm(TOPIC_PERM, ":topic." + topicFqtn, "view")); + aafService.shouldNotRemoveNamespace(); + } + + @Test + public void shouldHandleExceptionWhenPermissionRemovalWasFailed() { + aafService.givenRemovePermStatus(INTERNAL_SERVER_ERROR); + + ApiError apiError = aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldHandleExceptionWhenNamespaceRemovalWasFailed() { + aafService.givenRemoveNamespaceStatus(INTERNAL_SERVER_ERROR); + + ApiError apiError = aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + assertErrorStatus(apiError, INTERNAL_SERVER_ERROR); + } + + @Test + public void shouldNotPerformCleanupWhenDeleteLevelIsLessThanTwo() { + given(dmaapConfig.getProperty("MR.ClientDeleteLevel", "0")).willReturn("0"); + + ApiError apiError = aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + aafService.shouldNotPerformCleanup(); + assertOkStatus(apiError); + } + + @Test + public void shouldNotPerformCleanupWhenDeleteLevelIsNotNumericValue() { + given(dmaapConfig.getProperty("MR.ClientDeleteLevel", "0")).willReturn("not number"); + + ApiError apiError = aafTopicSetupService.aafTopicCleanup(givenTopic(TOPIC_FQTN)); + + aafService.shouldNotPerformCleanup(); + assertOkStatus(apiError); + } + + private Topic givenTopic(String topicFqtn) { + Topic topic = new Topic(); + topic.setFqtn(topicFqtn); + return topic; + } + + private void assertOkStatus(ApiError apiError) { + assertTrue(apiError.is2xx()); + assertEquals("OK", apiError.getMessage()); + } + + private void assertErrorStatus(ApiError apiError, int code) { + assertEquals(code, apiError.getCode()); + } + + private class AafServiceStub implements AafService { + + private AafNamespace addedNamespace; + private AafNamespace removedNamespace; + private List<DmaapPerm> addedPerms = newArrayList(); + private List<DmaapPerm> removedPerms = newArrayList(); + private List<AafRole> addedRoles = newArrayList(); + private List<DmaapGrant> addedGrants = newArrayList(); + private int addNamespaceStatus = CREATED; + private int addGrantStatus = CREATED; + private int addRoleStatus = CREATED; + private int addPermStatus = CREATED; + private int removePermStatus = OK; + private int removeNamespaceStatus = OK; + + @Override + public String getIdentity() { + return IDENTITY; + } + + @Override + public int addPerm(DmaapPerm perm) { + this.addedPerms.add(perm); + return addPermStatus; + } + + @Override + public int delPerm(DmaapPerm perm, boolean force) { + removedPerms.add(perm); + return removePermStatus; + } + + @Override + public int addGrant(DmaapGrant grant) { + addedGrants.add(grant); + return addGrantStatus; + } + + @Override + public int addUserRole(AafUserRole ur) { + throw new UnsupportedOperationException(); + } + + @Override + public int addRole(AafRole role) { + this.addedRoles.add(role); + return addRoleStatus; + } + + @Override + public int addNamespace(AafNamespace namespace) { + this.addedNamespace = namespace; + return addNamespaceStatus; + } + + @Override + public int delNamespace(AafNamespace namespace, boolean force) { + this.removedNamespace = namespace; + return removeNamespaceStatus; + } + + void givenReturnCode(int status) { + this.addNamespaceStatus = status; + this.addGrantStatus = status; + this.addRoleStatus = status; + this.addPermStatus = status; + this.removePermStatus = status; + this.removeNamespaceStatus = status; + } + + void givenAddNamespaceStatus(int addNamespaceStatus) { + this.addNamespaceStatus = addNamespaceStatus; + } + + void givenRemoveNamespaceStatus(int removeNamespaceStatus) { + this.removeNamespaceStatus = removeNamespaceStatus; + } + + void givenAddGrantStatus(int addGrantStatus) { + this.addGrantStatus = addGrantStatus; + } + + void givenAddRoleStatus(int addRoleStatus) { + this.addRoleStatus = addRoleStatus; + } + + void givenAddPermStatus(int addPermStatus) { + this.addPermStatus = addPermStatus; + } + + void givenRemovePermStatus(int removePermStatus) { + this.removePermStatus = removePermStatus; + } + + void shouldAddPerm(DmaapPerm perm) { + assertTrue(addedPerms.contains(perm)); + } + + void shouldRemovePerm(DmaapPerm perm) { + assertTrue(removedPerms.contains(perm)); + } + + void shouldAddNamespace(AafNamespace namespace) { + assertEquals(namespace, this.addedNamespace); + } + + void shouldRemoveNamespace(AafNamespace namespace) { + assertEquals(namespace, this.removedNamespace); + } + + void shouldAddRole(AafRole role) { + assertTrue(addedRoles.contains(role)); + } + + void shouldAddGrant(DmaapGrant grant) { + assertTrue(addedGrants.contains(grant)); + } + + void shouldHaveNoNamespaceRolesAndGrantsAdded() { + assertNull(this.addedNamespace); + assertTrue(this.addedGrants.isEmpty()); + assertTrue(this.addedRoles.isEmpty()); + } + + void shouldNotRemoveNamespace() { + assertNull(this.removedNamespace); + } + + void shouldNotPerformCleanup() { + shouldNotRemoveNamespace(); + assertTrue(removedPerms.isEmpty()); + } + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java new file mode 100644 index 0000000..c860e55 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ApiServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + ApiService ds; + + @Before + public void setUp() throws Exception { + ds = new ApiService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.service.ApiService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.ApiService", "set", v ); + + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/CredentialsParserTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/CredentialsParserTest.java new file mode 100644 index 0000000..ae5becc --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/CredentialsParserTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.service; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class CredentialsParserTest { + + private CredentialsParser credentialsParser = new CredentialsParser(); + + @Test + public void parse_shouldReturnEmptyCredentialsWhenAuthorizationHeaderIsNull() { + + Credentials credentials = credentialsParser.parse(null); + + assertTrue(credentials.getId().isEmpty()); + assertTrue(credentials.getPwd().isEmpty()); + } + + @Test + public void parse_shouldReturnEmptyCredentialsWhenAuthorizationHeaderIsEmpty() { + + Credentials credentials = credentialsParser.parse(""); + + assertTrue(credentials.getId().isEmpty()); + assertTrue(credentials.getPwd().isEmpty()); + } + + @Test + public void parse_shouldParseCorrectCredentials() { + + Credentials credentials = credentialsParser.parse("Basic dXNlcjpwYXNzd29yZA=="); + + assertEquals("user", credentials.getId()); + assertEquals("password", credentials.getPwd()); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DR_NodeServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DR_NodeServiceTest.java new file mode 100644 index 0000000..307d5b5 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DR_NodeServiceTest.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; + +public class DR_NodeServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + static DmaapObjectFactory factory = new DmaapObjectFactory(); + + DR_NodeService ns; + + @Before + public void setUp() throws Exception { + ns = new DR_NodeService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.service.DR_NodeService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.DR_NodeService", "set", v ); + + } + + @Test + public void test3() { + String f = "drsn01.onap.org"; + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = factory.genDcaeLocation( "central" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + DR_Node node = new DR_Node( f, locname, "zplvm009.onap.org", "1.0.46" ); + DR_Node n2 = ns.addDr_Node( node, err ); + + if ( n2 != null ) { + n2 = ns.getDr_Node( f, err ); + } + + List<DR_Node> l = ns.getAllDr_Nodes(); + if ( n2 != null ) { + n2.setVersion( "1.0.47" ); + n2 = ns.updateDr_Node( n2, err ); + } + + n2 = ns.removeDr_Node( f, err ); + + + } + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DcaeLocationServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DcaeLocationServiceTest.java new file mode 100644 index 0000000..e0b32a4 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DcaeLocationServiceTest.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.service; + +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.DmaapObject; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class DcaeLocationServiceTest { + + private static final String LOCATION_A = "locationA"; + private static final String LOCATION_B = "locationB"; + private DcaeLocationService locationService = new DcaeLocationService(new HashMap<>()); + + @Test + public void getAllDcaeLocations_shouldReturnEmptyCollection() { + + List<DcaeLocation> allDcaeLocations = locationService.getAllDcaeLocations(); + + assertTrue(allDcaeLocations.isEmpty()); + } + + @Test + public void addDcaeLocation_shouldAddLocationToMap() { + DcaeLocation locationA = createDcaeLocation(LOCATION_A); + + DcaeLocation addedLocation = locationService.addDcaeLocation(locationA); + + assertEquals(locationA, locationService.getDcaeLocation(LOCATION_A)); + assertSame(locationA, addedLocation); + } + + @Test + public void addDcaeLocation_shouldSetStatusAndLastModDate() { + DcaeLocation locationA = createDcaeLocation(LOCATION_A); + Date creationDate = new Date(10); + locationA.setLastMod(creationDate); + + DcaeLocation addedLocation = locationService.addDcaeLocation(locationA); + + assertTrue(addedLocation.getLastMod().after(creationDate)); + assertEquals(DmaapObject.DmaapObject_Status.VALID, addedLocation.getStatus()); + } + + @Test + public void updateDcaeLocation_shouldUpdateLocationAndLastModDate() { + DcaeLocation location = createDcaeLocation(LOCATION_A); + Date creationDate = new Date(10); + location.setLastMod(creationDate); + locationService.addDcaeLocation(location); + + DcaeLocation updatedLocation = locationService.updateDcaeLocation(location); + + assertTrue(updatedLocation.getLastMod().after(creationDate)); + assertSame(location, updatedLocation); + } + + @Test + public void updateDcaeLocation_shouldShouldReturnNullWhenLocationNameIsEmpty() { + DcaeLocation location = createDcaeLocation(""); + + DcaeLocation updatedLocation = locationService.updateDcaeLocation(location); + + assertNull(updatedLocation); + assertTrue(locationService.getAllDcaeLocations().isEmpty()); + } + + @Test + public void removeDcaeLocation_shouldRemoveLocationFromService() { + locationService.addDcaeLocation(createDcaeLocation(LOCATION_A)); + + locationService.removeDcaeLocation(LOCATION_A); + + assertTrue(locationService.getAllDcaeLocations().isEmpty()); + } + + @Test + public void getCentralLocation_shouldGetFirstCentralLocation() { + locationService.addDcaeLocation(createDcaeLocation(LOCATION_A, "layerA")); + locationService.addDcaeLocation(createDcaeLocation(LOCATION_B, "centralLayer")); + + assertEquals(LOCATION_B, locationService.getCentralLocation()); + } + + @Test + public void getCentralLocation_shouldReturnDefaultCentralLocationNameWhenThereIsNoCentralLocation() { + locationService.addDcaeLocation(createDcaeLocation(LOCATION_A, "layerA")); + + assertEquals("aCentralLocation", locationService.getCentralLocation()); + } + + @Test + public void isEdgeLocation_shouldReturnTrueForNotCentralLocation() { + locationService.addDcaeLocation(createDcaeLocation(LOCATION_A, "layerA")); + locationService.addDcaeLocation(createDcaeLocation(LOCATION_B, "centralLayer")); + + assertTrue(locationService.isEdgeLocation(LOCATION_A)); + assertFalse(locationService.isEdgeLocation(LOCATION_B)); + } + + @Test + public void isEdgeLocation_shouldReturnFalseWhenLocationDoesNotExist() { + locationService.addDcaeLocation(createDcaeLocation(LOCATION_A, "layerA")); + + assertFalse(locationService.isEdgeLocation("not_existing_location")); + } + + private DcaeLocation createDcaeLocation(String locationName) { + return createDcaeLocation(locationName, "dcaeLayer"); + } + + private DcaeLocation createDcaeLocation(String locationName, String dcaeLayer) { + return new DcaeLocation("clli", dcaeLayer, locationName, "openStackAvailabilityZone", "subnet"); + } + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java new file mode 100644 index 0000000..b8b660f --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class DmaapServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + DmaapService ds; + + @Before + public void setUp() throws Exception { + ds = new DmaapService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.service.DmaapService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.DmaapService", "set", v ); + + } + + @Test + public void test3() { + Dmaap nd = new Dmaap.DmaapBuilder().setVer("1").setTnr("org.onap.dmaap").setDn("onap-demo").setDpu("drps.demo.onap.org").setLu("").setBat("MMAGENT_TOPIC").setNk("").setAko("").createDmaap(); + ds.addDmaap( nd ); + } + + @Test + public void test4() { + Dmaap d = ds.getDmaap(); + + } + + @Test + public void test5() { + Dmaap nd = new Dmaap.DmaapBuilder().setVer("2").setTnr("org.onap.dmaap").setDn("onap-demo").setDpu("drps.demo.onap.org").setLu("").setBat("MMAGENT_TOPIC").setNk("").setAko("").createDmaap(); + ds.updateDmaap( nd ); + + } + + @Test + public void test6() { + String t = ds.getTopicPerm(); + String t2 = ds.getTopicPerm( "val2" ); + String t3 = ds.getBridgeAdminFqtn(); + + boolean b = ds.testCreateMmaTopic(); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/Dr_PubServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/Dr_PubServiceTest.java new file mode 100644 index 0000000..2cfe475 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/Dr_PubServiceTest.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; +import java.util.ArrayList; + +public class Dr_PubServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + DR_PubService ns; + FeedService fs; + + @Before + public void setUp() throws Exception { + ns = new DR_PubService(); + fs = new FeedService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.service.DR_PubService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.DR_PubService", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + Feed f = new Feed( "aTest", "1.0", "a unit test", "dgl", "unrestricted" ); + f = fs.addFeed( f, err ); + + assertTrue( f != null ); + DR_Pub node = new DR_Pub( locname, "aUser", "aPwd", f.getFeedId(), "pubId01" ); + DR_Pub n2 = ns.addDr_Pub( node ); + DR_Pub node2 = new DR_Pub( locname, "aUser", "aPwd", f.getFeedId() ); + n2 = ns.addDr_Pub( node2 ); + + if ( n2 != null ) { + n2 = ns.getDr_Pub( n2.getPubId(), err ); + } + + List<DR_Pub> l = ns.getAllDr_Pubs(); + if ( n2 != null ) { + n2 = ns.updateDr_Pub( n2 ); + } + + n2 = ns.removeDr_Pub( n2.getPubId(), err ); + + + } + + @Test + public void test4() { + ArrayList<DR_Pub> l = ns.getDr_PubsByFeedId( "1" ); + + + } + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java new file mode 100644 index 0000000..478647b --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class FeedServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + FeedService ds; + + @Before + public void setUp() throws Exception { + ds = new FeedService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.service.FeedService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.FeedService", "set", v ); + + } + + @Test + public void test3() { + ApiError err = new ApiError(); + + Feed f = new Feed( "aTest", "1.0", "a unit test", "dgl", "unrestricted" ); + f = ds.addFeed( f, err ); + System.out.println( "f=" + f ); + + ds.updateFeed( f, err ); + + ds.removeFeed( f, err ); + } + + @Test + public void test4() { + ApiError err = new ApiError(); + Feed f = ds.getFeed( "aName", err ); + + f = ds.getFeedByName( "aName", "1.0", err ); + + f = ds.getFeedPure( "aName", err ); + } + + @Test + public void test5() { + List<Feed> f = ds.getAllFeeds( "aName", "1.0", "startsWith" ); + + } + + + @Test + public void syncTestHard() { + ApiError err = new ApiError(); + ds.sync( true, err ); + + assert( 200 == err.getCode()); + } + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClientServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClientServiceTest.java new file mode 100644 index 0000000..e80697a --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClientServiceTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DcaeLocation; +import org.onap.dmaap.dbcapi.model.MR_Client; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +public class MR_ClientServiceTest { + + private static final String fmt = "%24s: %s%n"; + + private static DmaapObjectFactory factory = new DmaapObjectFactory(); + + ReflectionHarness rh = new ReflectionHarness(); + + private TopicService ts; + private MR_ClusterService mcs; + private MR_ClientService cls; + private DcaeLocationService dls; + + private String f; + private String locname; + + @Before + public void setUp() throws Exception { + ts = new TopicService(); + mcs = new MR_ClusterService(); + cls = new MR_ClientService(); + f = "mrsn01.onap.org"; + locname = "central-demo"; + + dls = new DcaeLocationService(); + DcaeLocation loc = factory.genDcaeLocation( "central" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] h = { "zplvm009.onap.org", "zplvm007.onap.org", "zplvm008.onap.org" }; + MR_Cluster node = factory.genMR_Cluster( "central" ); + MR_Cluster n2 = mcs.addMr_Cluster( node, err ); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.service.MR_ClientService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.MR_ClientService", "set", v ); + + } + + @Test + public void test3() { + Topic topic = factory.genSimpleTopic( "test3" ); + ApiError err = new ApiError(); + Topic nTopic = ts.addTopic( topic, err, false ); + if ( nTopic != null ) { + assertTrue( nTopic.getTopicName().equals( topic.getTopicName() )); + } + + MR_Client c = factory.genPublisher( "edge", topic.getFqtn() ); + + c = cls.addMr_Client( c, topic, err ); + + } + + @Test + public void test4() { + List<MR_Client> l = cls.getAllMr_Clients(); + + List<MR_Client> al = cls.getAllMrClients( "foo" ); + + List<MR_Client> al2 = cls.getClientsByLocation( "central" ); + } + + @Test + public void AddSubscriberToTopic() { + Topic topic = factory.genSimpleTopic( "test5" ); + ApiError err = new ApiError(); + Topic nTopic = ts.addTopic( topic, err, false ); + if ( nTopic != null ) { + assertTrue( nTopic.getTopicName().equals( topic.getTopicName() )); + } + MR_Client c = factory.genPublisher( "central", topic.getFqtn() ); + + c = cls.addMr_Client( c, topic, err ); + assertTrue( c != null ); + + c = factory.genSubscriber( "central", topic.getFqtn() ); + c = cls.addMr_Client( c, topic, err ); + assertTrue( err.getCode() == 200 ); + + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClusterServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClusterServiceTest.java new file mode 100644 index 0000000..8ae2667 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MR_ClusterServiceTest.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; + +public class MR_ClusterServiceTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + MR_ClusterService ns; + + @Before + public void setUp() throws Exception { + ns = new MR_ClusterService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.service.MR_ClusterService", "get", null ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.MR_ClusterService", "set", v ); + + } + + @Test + public void test3() { + String f = "mrsn01.onap.org"; + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "some-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] h = { "zplvm009.onap.org", "zplvm007.onap.org", "zplvm008.onap.org" }; + MR_Cluster node = new MR_Cluster( locname, f, "http", "3904"); + MR_Cluster n2 = ns.addMr_Cluster( node, err ); + + if ( n2 != null ) { + n2 = ns.getMr_Cluster( f, err ); + } + + List<MR_Cluster> l = ns.getAllMr_Clusters(); + if ( n2 != null ) { + n2 = ns.updateMr_Cluster( n2, err ); + } + + n2 = ns.removeMr_Cluster( f, err ); + + + } + +/* + @Test + public void test4() { + List<MR_Client> l = cls.getAllMr_Clients(); + + ArrayList<MR_Client> al = cls.getAllMrClients( "foo" ); + + ArrayList<MR_Client> al2 = cls.getClientsByLocation( "central" ); + } + + @Test + public void test5() { + Topic topic = new Topic(); + ApiError err = new ApiError(); + topic.setTopicName( "test3" ); + topic.setFqtnStyle( FqtnType.Validator("none") ); + topic.getFqtn(); + Topic nTopic = ts.addTopic( topic, err ); + if ( nTopic != null ) { + assertTrue( nTopic.getTopicName().equals( topic.getTopicName() )); + } + String[] actions = { "pub", "view" }; + MR_Client c = new MR_Client( "central-onap", "org.onap.dmaap.demo.interestingTopic2", "org.onap.clientApp.publisher", actions ); + + c = cls.addMr_Client( c, topic, err ); + if ( c != null ) { + actions[0] = "sub"; + c.setAction( actions ); + c = cls.updateMr_Client( c, err ); + assertTrue( err.getCode() == 200 ); + } + } +*/ + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTest.java new file mode 100644 index 0000000..f247bad --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTest.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.service; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; +import java.util.ArrayList; + +public class MirrorMakerServiceTest { + + private static final String fmt = "%24s: %s%n"; + private static DmaapObjectFactory factory = new DmaapObjectFactory(); + ReflectionHarness rh = new ReflectionHarness(); + + private MirrorMakerService mms; + private TopicService ts; + private MR_ClusterService mcs; + private MR_ClientService cls; + private DcaeLocationService dls; + + private Topic replicationTopic; + + + DmaapService ds; + String locname; + + @Before + public void setUp() throws Exception { + mms = new MirrorMakerService(); + ts = new TopicService(); + assert( ts != null ); + mcs = new MR_ClusterService(); + assert( mcs != null ); + Dmaap nd = factory.genDmaap(); + ds = new DmaapService(); + ds.addDmaap( nd ); + ts = new TopicService(); + mcs = new MR_ClusterService(); + cls = new MR_ClientService(); + + dls = new DcaeLocationService(); + DcaeLocation loc = factory.genDcaeLocation( "central" ); + locname = loc.getDcaeLocationName(); + dls.addDcaeLocation( loc ); + loc = factory.genDcaeLocation( "edge"); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + + MR_Cluster node = factory.genMR_Cluster( "central" ); + mcs.addMr_Cluster( node, err); + node = factory.genMR_Cluster("edge" ); + mcs.addMr_Cluster(node, err); + + + String t = "org.onap.dmaap.bridgingTopic"; + replicationTopic = factory.genSimpleTopic(t); + replicationTopic.setReplicationCase( ReplicationType.REPLICATION_EDGE_TO_CENTRAL ); + + String c = "publisher"; + String[] a = { "sub", "view" }; + MR_Client sub = factory.genMR_Client("central", replicationTopic.getFqtn(), c, a ); + String[] b = { "pub", "view" }; + MR_Client pub = factory.genMR_Client( "edge", replicationTopic.getFqtn(), c, b ); + ArrayList<MR_Client> clients = new ArrayList<MR_Client>(); + + clients.add( sub ); + clients.add( pub ); + + replicationTopic.setClients( clients ); + + } + + @After + public void tearDown() throws Exception { + } + + +// @Test +// public void test_getters() { +// +// +// rh.reflect( "org.onap.dmaap.dbcapi.service.MirrorMakerService", "get", null ); +// +// } + + @Test + public void test_setters() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.service.MirrorMakerService", "set", v ); + + } + + + + @Test + public void CreateMirrorMakerWithSingleTopic() { + ApiError err = new ApiError(); + + + Topic nTopic = ts.addTopic(replicationTopic, err, true ); + + assertTrue( err.getCode() == 200 ); + + List<String> mma = mms.getAllMirrorMakers(); + } + + @Test + public void DeleteMirrorMakerWithSingleTopic() { + + ApiError err = new ApiError(); + Topic nTopic = ts.addTopic(replicationTopic, err, true ); + replicationTopic.setTopicDescription("modified topic"); + nTopic = ts.updateTopic( replicationTopic, err ); + + assertTrue( err.getCode() == 200 ); + + + List<String> mma = mms.getAllMirrorMakers(); + + int nMM = mma.size(); + assertTrue( nMM >= 1); + + String name = mma.get(0); + + MirrorMaker mm = mms.getMirrorMaker(name); + + mms.delMirrorMaker(mm); + + mma = mms.getAllMirrorMakers(); + + assertTrue( mma.size() == (nMM-1) ); + } + + @Test + public void SplitMirrorMakerWithSingleTopic() { + + ApiError err = new ApiError(); + + + Topic nTopic = ts.addTopic( replicationTopic, err, true ); + replicationTopic.setTopicDescription("modified topic"); + nTopic = ts.updateTopic( replicationTopic, err ); + + + assertTrue( err.getCode() == 200 ); + List<String> mma = mms.getAllMirrorMakers(); + + int nMM = mma.size(); + assertTrue( nMM >= 1); + + String name = mma.get(0); + + MirrorMaker mm = mms.getMirrorMaker(name); + + MirrorMaker mm2 = mms.splitMM(mm); + + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTestMockito.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTestMockito.java new file mode 100644 index 0000000..5beadc6 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/MirrorMakerServiceTestMockito.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 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.dbcapi.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.onap.dmaap.dbcapi.model.MirrorMaker; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +@RunWith(MockitoJUnitRunner.class) +public class MirrorMakerServiceTestMockito { + + @Spy + private MirrorMakerService service; + + @Mock + private CadiFilter cadiFilterMock; + @Mock + private HttpServletRequest servletRequest; + @Mock + private HttpServletResponse servletResponse; + + @Mock + private DmaapConfig dmaapConfig; + + @Mock + private MirrorMaker mm = new MirrorMaker(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + + } + + @Test + public void init_normalConstructor() throws Exception { + //given + + + //when + + + //then + assertEquals( MirrorMakerService.getProvUserPwd(), MirrorMakerService.PROV_PWD_DEFAULT); + assertEquals( MirrorMakerService.getDefaultConsumerPort(), MirrorMakerService.TARGET_REPLICATION_PORT_DEFAULT); + assertEquals( MirrorMakerService.getDefaultProducerPort(), MirrorMakerService.SOURCE_REPLICATION_PORT_DEFAULT); + } + + // Todo: learn how to make more tests in Mockito + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/TopicServiceTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/TopicServiceTest.java new file mode 100644 index 0000000..a37ce02 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/service/TopicServiceTest.java @@ -0,0 +1,305 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.service; + +import com.google.common.collect.ImmutableMap; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.MR_Client; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.collect.Lists.newArrayList; +import static javax.ws.rs.core.Response.Status.NOT_FOUND; +import static javax.ws.rs.core.Response.Status.OK; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.onap.dmaap.dbcapi.model.ReplicationType.REPLICATION_GLOBAL_TO_FQDN; + +@RunWith(MockitoJUnitRunner.class) +public class TopicServiceTest { + + private static final String TOPIC_FQTN = "topic_1"; + private static final String GLOBAL_MR_HOST = "global.mr.host"; + private TopicService topicService; + @Mock + private MR_ClientService clientService; + @Mock + private DmaapConfig dmaapConfig; + @Mock + private MR_ClusterService clusters; + @Mock + private DcaeLocationService locations; + @Mock + private MirrorMakerService bridge; + @Mock + private AafTopicSetupService aafTopicSetupService; + + @Before + public void setUp() throws Exception { + given(dmaapConfig.getProperty("MR.globalHost", "global.host.not.set")).willReturn(GLOBAL_MR_HOST); + given(aafTopicSetupService.aafTopicSetup(any(Topic.class))).willReturn(new ApiError(200, "OK")); + given(aafTopicSetupService.aafTopicCleanup(any(Topic.class))).willReturn(new ApiError(200, "OK")); + createTopicService(); + } + + @Test + public void getTopics_shouldReturnTopicsReceivedDuringServiceCreation() { + + ImmutableMap<String, Topic> topics = ImmutableMap.of(TOPIC_FQTN, new Topic()); + topicService = new TopicService(topics, clientService, dmaapConfig, clusters, locations, bridge, aafTopicSetupService); + + assertEquals(topics, topicService.getTopics()); + } + + @Test + public void getAllTopics_shouldReturnTopicsWithClients() { + + ArrayList<MR_Client> mrClients = newArrayList(new MR_Client()); + given(clientService.getAllMrClients(TOPIC_FQTN)).willReturn(mrClients); + + List<Topic> allTopics = topicService.getAllTopics(); + + assertThat(getOnlyElement(allTopics), hasCorrectFqtn(TOPIC_FQTN)); + assertEquals(mrClients, getOnlyElement(allTopics).getClients()); + } + + @Test + public void getAllTopicsWithoutClients_shouldReturnNoClients() { + + List<Topic> allTopics = topicService.getAllTopicsWithoutClients(); + + assertThat(getOnlyElement(allTopics), hasCorrectFqtn(TOPIC_FQTN)); + assertNull(getOnlyElement(allTopics).getClients()); + verifyZeroInteractions(clientService); + } + + @Test + public void getAllTopics_shouldCacheClients() { + + ArrayList<MR_Client> mrClients = newArrayList(new MR_Client()); + given(clientService.getAllMrClients(TOPIC_FQTN)).willReturn(mrClients); + + topicService.getAllTopics(); + List<Topic> allTopics = topicService.getAllTopicsWithoutClients(); + + assertThat(getOnlyElement(allTopics), hasCorrectFqtn(TOPIC_FQTN)); + assertEquals(mrClients, getOnlyElement(allTopics).getClients()); + } + + @Test + public void getTopic_shouldReturnTopicByFqtn() { + + ApiError apiError = new ApiError(); + Topic topic = topicService.getTopic(TOPIC_FQTN, apiError); + + assertThat(topic, hasCorrectFqtn(TOPIC_FQTN)); + assertEquals(OK.getStatusCode(), apiError.getCode()); + } + + @Test + public void getTopic_shouldReturnTopicWithMrClients() { + + ArrayList<MR_Client> mrClients = newArrayList(new MR_Client()); + given(clientService.getAllMrClients(TOPIC_FQTN)).willReturn(mrClients); + + Topic topic = topicService.getTopic(TOPIC_FQTN, new ApiError()); + + assertThat(topic, hasCorrectFqtn(TOPIC_FQTN)); + assertEquals(mrClients, topic.getClients()); + } + + @Test + public void getTopic_shouldReturnError() { + + ApiError apiError = new ApiError(); + Topic topic = topicService.getTopic("not_existing", apiError); + + assertNull(topic); + assertEquals(NOT_FOUND.getStatusCode(), apiError.getCode()); + } + + @Test + public void addTopic_shouldAddNewTopic() { + Topic newTopic = createTopic(""); + + ApiError apiError = new ApiError(); + Topic addedTopic = topicService.addTopic(newTopic, apiError, true); + + assertSame(newTopic, addedTopic); + assertEquals(OK.getStatusCode(), apiError.getCode()); + assertNotNull(topicService.getTopic(addedTopic.getFqtn(), new ApiError())); + } + + @Test + public void addTopic_shouldReturnErrorWhenTopicAlreadyExists() { + Topic newTopic = createTopic(""); + + ApiError apiError = new ApiError(); + Topic addedTopic = topicService.addTopic(newTopic, apiError, false); + Topic secondAddedTopic = topicService.addTopic(addedTopic, apiError, false); + + assertNull(secondAddedTopic); + assertEquals(Response.Status.CONFLICT.getStatusCode(), apiError.getCode()); + } + + @Test + public void addTopic_shouldAddTheSameTopicWhenUseExistingIsSet() { + Topic newTopic = createTopic(""); + + ApiError apiError = new ApiError(); + Topic addedTopic = topicService.addTopic(newTopic, apiError, false); + Topic secondAddedTopic = topicService.addTopic(addedTopic, apiError, true); + + assertSame(addedTopic, secondAddedTopic); + assertEquals(OK.getStatusCode(), apiError.getCode()); + assertNotNull(topicService.getTopic(secondAddedTopic.getFqtn(), new ApiError())); + } + + + @Test + public void addTopic_shouldSetGlobalMrURL() { + Topic newTopic = createTopic(TOPIC_FQTN); + newTopic.setReplicationCase(REPLICATION_GLOBAL_TO_FQDN); + + ApiError apiError = new ApiError(); + Topic addedTopic = topicService.addTopic(newTopic, apiError, true); + + assertEquals(OK.getStatusCode(), apiError.getCode()); + assertEquals(GLOBAL_MR_HOST, addedTopic.getGlobalMrURL()); + } + + @Test + public void addTopic_shouldReturnErrorWhenGlobalMrURLIsInvalid() { + given(dmaapConfig.getProperty("MR.globalHost", "global.host.not.set")).willReturn("invalid@host"); + createTopicService(); + Topic newTopic = createTopic(TOPIC_FQTN); + newTopic.setReplicationCase(REPLICATION_GLOBAL_TO_FQDN); + + ApiError apiError = new ApiError(); + Topic addedTopic = topicService.addTopic(newTopic, apiError, true); + + assertEquals(500, apiError.getCode()); + assertNull(addedTopic); + } + + @Test + public void removeTopic_shouldFailIfTopicDoesNotExist() { + ApiError apiError = new ApiError(); + + Topic removedTopic = topicService.removeTopic("not_existing_fqtn", apiError); + + assertNull(removedTopic); + assertEquals(NOT_FOUND.getStatusCode(), apiError.getCode()); + assertTrue(topicService.getTopics().containsKey(TOPIC_FQTN)); + } + + @Test + public void removeTopic_shouldExecuteAafCleanup() { + ApiError apiError = new ApiError(); + + Topic removedTopic = topicService.removeTopic(TOPIC_FQTN, apiError); + + then(aafTopicSetupService).should().aafTopicCleanup(removedTopic); + assertEquals(OK.getStatusCode(), apiError.getCode()); + } + + @Test + public void removeTopic_shouldRemoveEachMrClientAssignedToTopic() { + ApiError apiError = new ApiError(); + MR_Client mrClient = new MR_Client(); + mrClient.setMrClientId("mrClientId"); + + given(clientService.getAllMrClients(TOPIC_FQTN)).willReturn(newArrayList(mrClient)); + + topicService.removeTopic(TOPIC_FQTN, apiError); + + then(clientService).should().removeMr_Client(mrClient.getMrClientId(), false, apiError); + assertEquals(OK.getStatusCode(), apiError.getCode()); + } + + @Test + public void removeTopic_shouldRemoveTopicFromCache() { + ApiError apiError = new ApiError(); + + topicService.removeTopic(TOPIC_FQTN, apiError); + + assertTrue(topicService.getTopics().isEmpty()); + assertEquals(OK.getStatusCode(), apiError.getCode()); + } + + @Test + public void removeTopic_shouldFailIfAafCleanupWasFailed() { + ApiError apiError = new ApiError(); + given(aafTopicSetupService.aafTopicCleanup(any(Topic.class))).willReturn(new ApiError(404, "sth went wrong")); + + Topic removedTopic = topicService.removeTopic(TOPIC_FQTN, apiError); + + assertNull(removedTopic); + assertEquals(404, apiError.getCode()); + assertTrue(topicService.getTopics().containsKey(TOPIC_FQTN)); + } + + private void createTopicService() { + Map<String, Topic> mrTopics = new HashMap<>(); + mrTopics.put(TOPIC_FQTN, createTopic(TOPIC_FQTN)); + topicService = new TopicService(mrTopics, clientService, dmaapConfig, clusters, locations, bridge, aafTopicSetupService); + } + + private Topic createTopic(String fqtn) { + return new Topic(fqtn, "name", "desc", "tnxEnabled", "owner"); + } + + public static Matcher<Topic> hasCorrectFqtn(final String fqtn) { + return new BaseMatcher<Topic>() { + public boolean matches(Object o) { + return fqtn.equals(((Topic) o).getFqtn()); + } + + public void describeTo(Description description) { + description.appendText("Topics should should be equal. Expected fqtn: ").appendValue(fqtn); + } + }; + } + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/DmaapObjectFactory.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/DmaapObjectFactory.java new file mode 100644 index 0000000..9d45a54 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/DmaapObjectFactory.java @@ -0,0 +1,128 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.testframework; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.util.RandomInteger; + +public class DmaapObjectFactory { + + /* + * we use localhost for most references so that connection attempts will resolve and not retry + * but still we expect that requests will fail. + */ + private static final String fmt = "%24s: %s%n"; + private static final String dmaap_name = "onap-ut"; + private static final String dmaap_ver = "1"; + private static final String dmaap_topic_root = "org.onap.dmaap"; + private static final String dmaap_dr = "https://localhost:8443"; + private static final String dmaap_log_url = "http://localhost:8080/log"; + private static final String dmaap_mm_topic = "org.onap.dmaap.dcae.MM_AGENT_TOPIC"; + private static final String central_loc = "SanFrancisco"; + private static final String central_layer = "central-cloud"; + private static final String central_clli = "SFCAL19240"; + private static final String central_zone = "osaz01"; + private static final String central_subnet = "10.10.10.0/24"; + private static final String central_cluster_fqdn = "localhost"; + private static final String pub_role = "org.onap.vnfapp.publisher"; + private static final String sub_role = "org.onap.vnfapp.subscriber"; + private static final String edge_loc = "Atlanta"; + private static final String edge_layer = "edge-cloud"; + private static final String edge_clli = "ATLGA10245"; + private static final String edge_zone = "osaz02"; + private static final String edge_subnet = "10.10.20.0/24"; + private static final String edge_cluster_fqdn = "localhost"; + private static final String[]hosts = { "host1", "host2", "host3" }; + private static final String port = "3904"; + private static final String prot = "http"; + + public Dmaap genDmaap() { + return new Dmaap.DmaapBuilder().setVer(dmaap_ver).setTnr(dmaap_topic_root).setDn(dmaap_name).setDpu(dmaap_dr).setLu(dmaap_log_url).setBat(dmaap_mm_topic).setNk("nk").setAko("ako").createDmaap(); + } + + public DcaeLocation genDcaeLocation( String layer ) { + if ( layer.contains( "edge" ) ) { + return new DcaeLocation( edge_clli, edge_layer, edge_loc, edge_zone, edge_subnet ); + } + return new DcaeLocation( central_clli, central_layer, central_loc, central_zone, central_subnet ); + } + + + public MR_Cluster genMR_Cluster( String layer ) { + if ( layer.contains( "edge" ) ) { + return new MR_Cluster( edge_loc, edge_cluster_fqdn, prot, port ); + } + return new MR_Cluster( central_loc, central_cluster_fqdn, prot, port ); + } + + public Topic genSimpleTopic( String tname ) { + Topic t = new Topic(); + t.setTopicName( tname ); + t.setFqtnStyle( FqtnType.Validator("none") ); + t.setTopicDescription( "a simple Topic named " + tname ); + t.setOwner( "ut"); + t.setFqtn(t.genFqtn()); + return t; + } + + public MR_Client genMR_Client( String l, String f, String r, String[] a ) { + if ( l.contains( "edge" ) ) { + return new MR_Client( edge_loc, f, r, a ); + } + return new MR_Client( central_loc, f, r, a ); + } + + public MR_Client genPublisher( String layer, String fqtn ) { + String[] actions = { "pub", "view" }; + return genMR_Client( layer, fqtn, pub_role, actions ); + } + public MR_Client genSubscriber( String layer, String fqtn ) { + String[] actions = { "sub", "view" }; + return genMR_Client( layer, fqtn, sub_role, actions ); + } + + public DR_Sub genDrSub( String l, String feed ) { + String un = "user1"; + String up = "secretW0rd"; + String du = "sub.server.onap.org:8443/deliver/here"; + String lu = "https://drps.onap.org:8443/sublog/123"; + boolean u100 = true; + + if ( l.contains( "edge" ) ) { + return new DR_Sub( edge_loc, un, up, feed, du, lu, u100 ); + } + return new DR_Sub( central_loc, un, up, feed, du, lu, u100 ); + } + + public DR_Node genDR_Node( String l ) { + String version = "1.0.1"; + RandomInteger ri = new RandomInteger( 1000 ); + int i = ri.next(); + String fqdn = String.format( "drns%d.onap.org", i ); + String host = String.format( "host%d.onap.org", i ); + + if ( l.contains( "edge" ) ) { + return new DR_Node( fqdn, edge_loc, host, version ); + } + return new DR_Node( fqdn, central_loc, host, version ); + } + + +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/ReflectionHarness.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/ReflectionHarness.java new file mode 100644 index 0000000..be4b754 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/testframework/ReflectionHarness.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.testframework; + +import static java.lang.System.err; +import static java.lang.System.out; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +public class ReflectionHarness { + private static final String fmt = "%24s: %s%n"; + + + // following 2 functions taken from: http://tutorials.jenkov.com/java-reflection/getters-setters.html + public static boolean isGetter(Method method){ + if(!method.getName().startsWith("get")) return false; + if(method.getParameterTypes().length != 0) return false; + if(void.class.equals(method.getReturnType())) return false; + return true; + } + + public static boolean isSetter(Method method){ + if(!method.getName().startsWith("set")) return false; + if(method.getParameterTypes().length != 1) return false; + return true; + } + + private void testGetter( Class<?> c, Method m, Class<?>[] pType, String val ) { + out.format( fmt, "testGetter: Method Name", m.getName() ); + Class retType = m.getReturnType(); + out.format( fmt, "testGetter: Return Type ", retType ); + out.format( fmt, "testGetter: val ", (val != null)?val:"null" ); + assertTrue( pType.length == 0 ); + + try { + Object t = c.newInstance(); + + try { + m.setAccessible(true); + Object o = m.invoke( t ); + + if( retType.equals( Class.forName( "java.lang.String" ) ) ) { + if ( val == null ) { + out.format( fmt, "testGetter: expected null, got ", (o != null)?o:"null" ); + assert( o == null ); + } else { + out.format( fmt, "testGetter: expected val, got ", (o != null)?o:"null" ); + assert( o.equals( val ) ); + } + } else { + out.format( fmt, "testGetter: " + m.getName() + " untested retType", retType ); + + } + + } catch (InvocationTargetException e ) { + Throwable cause = e.getCause(); + err.format( "%s() returned %x%n", m.getName(), cause.getMessage() ); + } + + } catch (ClassNotFoundException nfe ){ + nfe.printStackTrace(); + } catch (IllegalArgumentException ae ) { + ae.printStackTrace(); + } catch (InstantiationException ie ) { + ie.printStackTrace(); + } catch (IllegalAccessException iae ) { + iae.printStackTrace(); + } + } + + private void testSetter( Class<?> c, Method m, Class<?>[] pType ) { + //out.format( fmt, "testSetter: Method Name", m.getName() ); + Class retType = m.getReturnType(); + //out.format( fmt, "testSetter: Return Type ", retType ); + //out.format( fmt, "testSetter: val ", (val != null)?val:"null" ); + assertTrue( pType.length == 1 ); + + try { + Object t = c.newInstance(); + + try { + m.setAccessible(true); + //out.format( fmt, "testSetter: " + m.getName() + " to try pType", pType[0] ); + if ( pType[0].equals( Class.forName( "java.lang.String" ) ) ) { + String val = "Validate123"; + Object o = m.invoke( t, val ); + } else if ( pType[0].equals( boolean.class ) ) { // note primitive class notation + boolean b = true; + Object o = m.invoke( t, b ); + } else { + out.format( fmt, "testSetter: " + m.getName() + " untested pType", pType[0] ); + } + + } catch (InvocationTargetException e ) { + Throwable cause = e.getCause(); + err.format( "%s() returned %x%n", m.getName(), cause.getMessage() ); + } + + } catch (ClassNotFoundException nfe ){ + nfe.printStackTrace(); + } catch (IllegalArgumentException ae ) { + ae.printStackTrace(); + } catch (InstantiationException ie ) { + ie.printStackTrace(); + } catch (IllegalAccessException iae ) { + iae.printStackTrace(); + } + } + + public void reflect(String... args) { + try { + Class<?> c = Class.forName(args[0]); + Method[] allMethods = c.getDeclaredMethods(); + String methodPrefix = args[1]; + for (Method m : allMethods) { + if (!m.getName().startsWith(methodPrefix)) { + continue; + } + //out.format("%s%n", m.toGenericString()); + + //out.format(fmt, "ReturnType", m.getReturnType()); + //out.format(fmt, "GenericReturnType", m.getGenericReturnType()); + + Class<?>[] pType = m.getParameterTypes(); + Type[] gpType = m.getGenericParameterTypes(); + for (int i = 0; i < pType.length; i++) { + //out.format(fmt,"ParameterType", pType[i]); + //out.format(fmt,"GenericParameterType", gpType[i]); + } + if ( isGetter( m ) ) { + testGetter( c, m, pType , args[2]); + } else if ( isSetter( m ) ) { + testSetter( c, m, pType ); + } + + Class<?>[] xType = m.getExceptionTypes(); + Type[] gxType = m.getGenericExceptionTypes(); + for (int i = 0; i < xType.length; i++) { + //out.format(fmt,"ExceptionType", xType[i]); + //out.format(fmt,"GenericExceptionType", gxType[i]); + } + } + + // production code should handle these exceptions more gracefully + } catch (ClassNotFoundException x) { + x.printStackTrace(); + } + } +} diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapConfigTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapConfigTest.java new file mode 100644 index 0000000..6ef05c0 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapConfigTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.util; + +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DmaapConfigTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + DmaapConfig g; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.util.DmaapConfig", "get", "" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.util.DmaapConfig", "set", v ); + + } + + @Test + public void test3() { + + String f = g.getConfigFileName(); + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapTimestampTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapTimestampTest.java new file mode 100644 index 0000000..33d1d17 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/DmaapTimestampTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.util; + +import org.junit.Test; + +import java.util.Date; + +import static org.junit.Assert.assertTrue; + +public class DmaapTimestampTest { + + private DmaapTimestamp dmaapTimestamp = new DmaapTimestamp(); + + @Test + public void mark_shouldUpdateTimestamp() { + dmaapTimestamp = new DmaapTimestamp(new Date(10)); + Date timestamp = dmaapTimestamp.getVal(); + + dmaapTimestamp.mark(); + + assertTrue(timestamp.before(dmaapTimestamp.getVal())); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/FqdnTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/FqdnTest.java new file mode 100644 index 0000000..7c7815f --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/FqdnTest.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 IBM 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.dbcapi.util; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class FqdnTest { + + @Test + public void testIsValid() { + assertTrue(Fqdn.isValid("www.ibm.com")); + assertFalse(Fqdn.isValid("testuser@ibm.com")); + } +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/GraphTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/GraphTest.java new file mode 100644 index 0000000..770ee65 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/GraphTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 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.dbcapi.util; + +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; + +public class GraphTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + Graph g; + + + @Before + public void setUp() throws Exception { + HashMap<String, String> hm = new HashMap<String,String>(); + g = new Graph( hm ); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.util.Graph", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.util.Graph", "set", v ); + + } + + @Test + public void test3() { + String loc = "central-onap"; + String[] actions = { "pub", "sub" }; + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation dl = new DcaeLocation( "CLLI123", "central-layer", loc, "aZone", "10.10.10.10" ); + dls.addDcaeLocation( dl ); + MR_Client mrc = new MR_Client(); + mrc.setAction( actions ); + List<MR_Client> cl = new ArrayList<MR_Client>(); + cl.add( mrc ); + cl.add( new MR_Client( loc, "aTopic", "ignore", actions ) ); + + g = new Graph( cl, true ); + + HashMap<String, String> hm = new HashMap<String, String>(); + + + String s = g.put( "aKey", "aVal" ); + s = g.get( "aKey" ); + + s = g.getCentralLoc(); + g.setHasCentral( true ); + g.hasCentral(); + + hm = g.getGraph(); + + Collection<String> k = g.getKeys(); + + } + + + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/PermissionBuilderTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/PermissionBuilderTest.java new file mode 100644 index 0000000..8db9d2e --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/PermissionBuilderTest.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.util; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import javax.servlet.http.HttpServletRequest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status; +import org.onap.dmaap.dbcapi.service.DmaapService; + +@RunWith(MockitoJUnitRunner.class) +public class PermissionBuilderTest { + + private static final String DMAAP_NAME = "mr"; + private PermissionBuilder permissionBuilder; + @Mock + private DmaapConfig dmaapConfig; + @Mock + private DmaapService dmaapService; + @Mock + private HttpServletRequest request; + + + @Test + public void updateDmaapInstance_shouldSetBootInstance_whenDmaapIsNotInitialized() { + //given + doReturn(null).when(dmaapService).getDmaap(); + permissionBuilder = new PermissionBuilder(dmaapConfig, dmaapService); + + //when + permissionBuilder.updateDmaapInstance(); + + //then + assertEquals(PermissionBuilder.BOOT_INSTANCE, permissionBuilder.getInstance()); + } + + @Test + public void updateDmaapInstance_shouldSetBootInstance_whenDmaapIsInitializedWithDefaultInstance() { + //given + doReturn(provideDefaultInstance()).when(dmaapService).getDmaap(); + permissionBuilder = new PermissionBuilder(dmaapConfig, dmaapService); + + //when + permissionBuilder.updateDmaapInstance(); + + //then + assertEquals(PermissionBuilder.BOOT_INSTANCE, permissionBuilder.getInstance()); + } + + @Test + public void updateDmaapInstance_shouldSetRealInstance_whenDmaapServiceProvidesOne() { + //given + when(dmaapService.getDmaap()).thenReturn(provideDefaultInstance(), provideRealInstance(DMAAP_NAME)); + permissionBuilder = new PermissionBuilder(dmaapConfig, dmaapService); + + //when + permissionBuilder.updateDmaapInstance(); + + //then + assertEquals(DMAAP_NAME, permissionBuilder.getInstance()); + } + + @Test + public void updateDmaapInstance_shouldNotUpdateDmaapInstance_whenAlreadyInitializedWithRealInstance() { + //given + when(dmaapService.getDmaap()).thenReturn(provideRealInstance(DMAAP_NAME), provideRealInstance("newName")); + permissionBuilder = new PermissionBuilder(dmaapConfig, dmaapService); + + //when + permissionBuilder.updateDmaapInstance(); + + //then + assertEquals(DMAAP_NAME, permissionBuilder.getInstance()); + verify(dmaapService, atMost(1)).getDmaap(); + } + + @Test + public void buildPermission_shouldBuildPermissionWithBootInstance() { + //given + String path = "/dmaap"; + String method = "GET"; + initPermissionBuilder(path, method, provideDefaultInstance()); + + //when + String permission = permissionBuilder.buildPermission(request); + + //then + assertEquals("org.onap.dmaap-bc.api.dmaap|boot|GET", permission); + } + + @Test + public void buildPermission_shouldBuildPermissionWithRealInstance() { + //given + String path = "/dmaap"; + String method = "GET"; + initPermissionBuilder(path, method, provideRealInstance(DMAAP_NAME)); + + //when + String permission = permissionBuilder.buildPermission(request); + + //then + assertEquals("org.onap.dmaap-bc.api.dmaap|mr|GET", permission); + } + + @Test + public void buildPermission_shouldBuildPermissionWhenUrlContainsId() { + //given + String path = "/topics/topic_id_123"; + String method = "GET"; + initPermissionBuilder(path, method, provideRealInstance(DMAAP_NAME)); + + //when + String permission = permissionBuilder.buildPermission(request); + + //then + assertEquals("org.onap.dmaap-bc.api.topics|mr|GET", permission); + } + + private void initPermissionBuilder(String path, String method, Dmaap dmaapInstance) { + when(dmaapConfig.getProperty(PermissionBuilder.API_NS_PROP, PermissionBuilder.DEFAULT_API_NS)) + .thenReturn(PermissionBuilder.DEFAULT_API_NS); + when(dmaapService.getDmaap()).thenReturn(dmaapInstance); + permissionBuilder = new PermissionBuilder(dmaapConfig, dmaapService); + + when(request.getPathInfo()).thenReturn(path); + when(request.getMethod()).thenReturn(method); + } + + private Dmaap provideDefaultInstance() { + return new Dmaap.DmaapBuilder().setVer("0").setTnr("").setDn("").setDpu("").setLu("").setBat("").setNk("").setAko("").createDmaap(); + } + + private Dmaap provideRealInstance(String dmaapName) { + Dmaap dmaap = new Dmaap.DmaapBuilder().setVer("1").setTnr("org.onap.dmaap").setDn(dmaapName).setDpu("https://dmaap-dr-prov:8443").setLu("").setBat("DCAE_MM_AGENT").setNk("").setAko("").createDmaap(); + dmaap.setStatus(DmaapObject_Status.VALID); + return dmaap; + } + +}
\ No newline at end of file diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomIntegerTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomIntegerTest.java new file mode 100644 index 0000000..1184cdb --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomIntegerTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.util; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class RandomIntegerTest { + + private static final int RANGE = 10; + private RandomInteger ri = new RandomInteger(RANGE); + + @Test + public void next_shouldReturnIntegerFromGivenRange() { + + int next = ri.next(); + + assertTrue(next >= 0 && next <= RANGE); + } + +} + diff --git a/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomStringTest.java b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomStringTest.java new file mode 100644 index 0000000..e549dc3 --- /dev/null +++ b/dmaap-bc/src/test/java/org/onap/dmaap/dbcapi/util/RandomStringTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2019 Nokia 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.dbcapi.util; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class RandomStringTest { + + private static final int LENGTH = 10; + @Rule + public ExpectedException thrown = ExpectedException.none(); + private RandomString randomString = new RandomString(LENGTH); + + @Test + public void nextString_shouldReturnStringWithGivenLength() { + + String nextString = randomString.nextString(); + + assertEquals(LENGTH, nextString.length()); + } + + @Test + public void nextString_shouldReturnAlphanumeric() { + + String nextString = randomString.nextString(); + + assertTrue(nextString.matches("[a-z0-9]*")); + } + + @Test + public void constructor_shouldThrowExceptionForNegativeLength() { + + thrown.expect(IllegalArgumentException.class); + + new RandomString(-1); + } +}
\ No newline at end of file |