diff --git a/notification-core/pom.xml b/notification-core/pom.xml index c77f6b34d8298e5f338a44a6ad5a6af3b6acb065..838addd6e74505183519c74ddbc2c732222c9d4e 100644 --- a/notification-core/pom.xml +++ b/notification-core/pom.xml @@ -290,27 +290,45 @@ <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.2</version> + <configuration> + <excludes> + <exclude>**/models/*</exclude> + <exclude>**/swagger/*</exclude> + </excludes> + </configuration> + <executions> <execution> - <id>prepare-unit-tests</id> + <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> - - <!-- prepare agent for measuring integration tests --> <execution> - <id>prepare-agent</id> + <id>report</id> + <phase>prepare-package</phase> <goals> - <goal>prepare-agent</goal> + <goal>report</goal> </goals> - <phase>pre-integration-test</phase> - <configuration> - <propertyName>itCoverageAgent</propertyName> - </configuration> </execution> </executions> </plugin> </plugins> </build> + <reporting> + <plugins> + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <reportSets> + <reportSet> + <reports> + <!-- select non-aggregate reports --> + <report>report</report> + </reports> + </reportSet> + </reportSets> + </plugin> + </plugins> + </reporting> </project> diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/api/GlobalErrorControllerTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/api/GlobalErrorControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6c4570a42587a93a1fcaf22703c41c44588e6bc7 --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/api/GlobalErrorControllerTest.java @@ -0,0 +1,86 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.api; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GlobalErrorControllerTest { + + @Mock + HttpServletRequest httpServletRequest; + + @InjectMocks + private GlobalErrorController globalErrorController; + + @Before + public void setup() { + MockitoAnnotations.initMocks(GlobalErrorControllerTest.this); + when(httpServletRequest.getAttribute(eq("javax.servlet.error.exception"))).thenReturn(new Exception("sample exception")); + } + + @Test + public void handleErrorGetTest() { + when(httpServletRequest.getAttribute(eq("javax.servlet.error.status_code"))).thenReturn(500); + String expected = globalErrorController.handleErrorGet(httpServletRequest); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); + } + + @Test + public void handleErrorPutTest() { + when(httpServletRequest.getAttribute(eq("javax.servlet.error.status_code"))).thenReturn(404); + String expected = globalErrorController.handleErrorPut(httpServletRequest); + assertEquals(expected, "{\"code\": 404, \"reason:\": \"Not Found\" \"message\":\"sample exception\" }"); + } + + @Test + public void handleErrorPatchTest() { + when(httpServletRequest.getAttribute(eq("javax.servlet.error.status_code"))).thenReturn(500); + String expected = globalErrorController.handleErrorPatch(httpServletRequest); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); + } + + @Test + public void handleErrorDeleteTest() { + when(httpServletRequest.getAttribute(eq("javax.servlet.error.status_code"))).thenReturn(500); + String expected = globalErrorController.handleErrorDelete(httpServletRequest); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); + } + + @Test + public void handleErrorPostTest() { + when(httpServletRequest.getAttribute(eq("javax.servlet.error.status_code"))).thenReturn(500); + String expected = globalErrorController.handleErrorPost(httpServletRequest); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); + } + + @Test + public void getErrorPathTest() { + assertEquals(globalErrorController.getErrorPath(), "/error"); + } + +} \ No newline at end of file diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/api/InfoApiTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/api/InfoApiTest.java index 1b694967b57ecbb481b06a006cf4bf8ed8048234..58f021b44587f4de1ad3b5d53802243e39d37c72 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/api/InfoApiTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/api/InfoApiTest.java @@ -17,11 +17,6 @@ package org.opengroup.osdu.notification.api; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.io.IOException; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -32,33 +27,38 @@ import org.mockito.junit.MockitoJUnitRunner; import org.opengroup.osdu.core.common.info.VersionInfoBuilder; import org.opengroup.osdu.core.common.model.info.VersionInfo; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class InfoApiTest { - @InjectMocks - private InfoApi sut; + @InjectMocks + private InfoApi sut; - @Mock - private VersionInfoBuilder versionInfoBuilder; + @Mock + private VersionInfoBuilder versionInfoBuilder; - @Before - public void setup(){ - MockitoAnnotations.initMocks(InfoApiTest.this); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(InfoApiTest.this); + } - @Test - public void should_return200_getVersionInfo() throws IOException { - VersionInfo versionInfo = VersionInfo.builder() - .groupId("group") - .artifactId("artifact") - .version("0.1.0") - .buildTime("1000") - .branch("master") - .commitId("7777") - .commitMessage("Merge commit") - .build(); - when(versionInfoBuilder.buildVersionInfo()).thenReturn(versionInfo); - VersionInfo response = this.sut.info(); - assertEquals(versionInfo, response); - } + @Test + public void should_return200_getVersionInfo() throws IOException { + VersionInfo versionInfo = VersionInfo.builder() + .groupId("group") + .artifactId("artifact") + .version("0.1.0") + .buildTime("1000") + .branch("master") + .commitId("7777") + .commitMessage("Merge commit") + .build(); + when(versionInfoBuilder.buildVersionInfo()).thenReturn(versionInfo); + VersionInfo response = this.sut.info(); + assertEquals(versionInfo, response); + } } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTests.java b/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java similarity index 90% rename from notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTests.java rename to notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java index 982ea856510f86c07ccc4336e28d0545fa4ee00d..ebc388a71ce54795ee0a9212085d817f2265a5d4 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTests.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java @@ -25,35 +25,34 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.opengroup.osdu.core.common.http.HttpResponse; import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; -import org.opengroup.osdu.core.common.model.http.DpsHeaders; -import org.opengroup.osdu.core.common.notification.SubscriptionException; import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; import org.opengroup.osdu.notification.service.NotificationHandler; -import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.ResponseEntity; import java.util.HashMap; import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) -public class PubsubEndpointTests { +public class PubsubEndpointTest { + + private static final String NOTIFICATION_ID = "test-notification-id"; + private static final String PUBSUB_MESSAGE = "test-pubsub-message-data"; + private final HttpResponse response = new HttpResponse(); + @Mock private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor; + @Mock private NotificationHandler notificationHandler; + @Mock private JaxRsDpsLog log; + @InjectMocks private PubsubEndpoint sut; - private static final String NOTIFICATION_ID = "test-notification-id"; - private static final String PUBSUB_MESSAGE = "test-pubsub-message-data"; - private HttpResponse response = new HttpResponse(); - @Before public void setup() throws Exception { when(this.pubsubRequestBodyExtractor.extractNotificationIdFromRequestBody()).thenReturn(NOTIFICATION_ID); diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationFilterTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationFilterTest.java index 61f0520808162f345ac2c6f4645d0247a480ee60..44cfac89b8fb4d17fa2a8ceb07740d18aa3e93d2 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationFilterTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationFilterTest.java @@ -27,8 +27,8 @@ import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.opengroup.osdu.core.common.provider.interfaces.IAuthorizationService; import org.opengroup.osdu.notification.di.RequestInfoExt; import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; -import org.opengroup.osdu.notification.utils.Config; import org.opengroup.osdu.notification.provider.interfaces.IServiceAccountValidator; +import org.opengroup.osdu.notification.utils.Config; import org.powermock.modules.junit4.PowerMockRunner; import javax.servlet.http.HttpServletRequest; @@ -53,16 +53,22 @@ public class AuthorizationFilterTest { @Mock private DpsHeaders headers; + @Mock private HttpServletRequest request; + @Mock private RequestInfoExt requestInfo; + @Mock private IAuthorizationService authorizationService; + @Mock private IServiceAccountValidator validator; + @Mock private IPubsubRequestBodyExtractor extractor; + @InjectMocks private AuthorizationFilter sut; @@ -87,7 +93,6 @@ public class AuthorizationFilterTest { public void should_throwAppError_when_noAuthzProvided() { when(headers.getAuthorization()).thenReturn(""); final String USER_EMAIL = "test@test.com"; - this.sut.hasAnyPermission(ROLE1, ROLE2); assertEquals(USER_EMAIL, this.headers.getUserEmail()); } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationServiceEntitlementsTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationServiceEntitlementsTest.java index cd9a70007afaf20958ba2714cba7535d930eb170..722c856aa9267b95ddfcae9252ec50641ced47b0 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationServiceEntitlementsTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/AuthorizationServiceEntitlementsTest.java @@ -16,6 +16,12 @@ package org.opengroup.osdu.notification.auth; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.opengroup.osdu.core.common.entitlements.AuthorizationServiceImpl; import org.opengroup.osdu.core.common.entitlements.IEntitlementsFactory; import org.opengroup.osdu.core.common.entitlements.IEntitlementsService; import org.opengroup.osdu.core.common.http.HttpResponse; @@ -24,14 +30,8 @@ import org.opengroup.osdu.core.common.model.entitlements.AuthorizationResponse; import org.opengroup.osdu.core.common.model.entitlements.EntitlementsException; import org.opengroup.osdu.core.common.model.entitlements.GroupInfo; import org.opengroup.osdu.core.common.model.entitlements.Groups; -import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.opengroup.osdu.core.common.model.http.AppException; -import org.opengroup.osdu.core.common.entitlements.AuthorizationServiceImpl; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; @@ -48,50 +48,50 @@ public class AuthorizationServiceEntitlementsTest { @Mock private IEntitlementsFactory entitlementsFactory; + @Mock private IEntitlementsService service; + @Mock private JaxRsDpsLog log; + @InjectMocks private AuthorizationServiceImpl sut; @Before - public void setup(){ + public void setup() { when(entitlementsFactory.create(any())).thenReturn(service); } @Test - public void should_returnUser_when_ussrHasPermission()throws EntitlementsException { + public void should_returnUser_when_userHasPermission() throws EntitlementsException { sut = createSut("service.register.user"); - AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user"); assertEquals("akelham@bbc.com", result.getUser()); } @Test - public void should_returnUser_when_ussrHasAnyPermission()throws EntitlementsException { + public void should_returnUser_when_userHasAnyPermission() throws EntitlementsException { sut = createSut("service.register.editor"); - AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user", "service.register.editor"); assertEquals("akelham@bbc.com", result.getUser()); } @Test - public void should_throwUnauthorized_when_userDoesNotHaveRequiredPermission()throws EntitlementsException { + public void should_throwUnauthorized_when_userDoesNotHaveRequiredPermission() throws EntitlementsException { sut = createSut("service.register.user"); - try { sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); fail("expected exception"); - }catch(AppException ex){ + } catch (AppException ex) { assertEquals(401, ex.getError().getCode()); } } @Test - public void should_throwServerError_when_getGroupsThrowsServerError()throws EntitlementsException { + public void should_throwServerError_when_getGroupsThrowsServerError() throws EntitlementsException { sut = createSut("service.register.user"); HttpResponse response = new HttpResponse(); response.setResponseCode(500); @@ -99,13 +99,13 @@ public class AuthorizationServiceEntitlementsTest { try { sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); fail("expected exception"); - }catch(AppException ex){ + } catch (AppException ex) { assertEquals(500, ex.getError().getCode()); } } @Test - public void should_throw400AppError_when_getGroupsThrows400EntitlementsError()throws EntitlementsException { + public void should_throw400AppError_when_getGroupsThrows400EntitlementsError() throws EntitlementsException { sut = createSut("service.register.user"); HttpResponse response = new HttpResponse(); response.setResponseCode(400); @@ -113,7 +113,7 @@ public class AuthorizationServiceEntitlementsTest { try { sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); fail("expected exception"); - }catch(AppException ex){ + } catch (AppException ex) { assertEquals(400, ex.getError().getCode()); } } @@ -121,7 +121,7 @@ public class AuthorizationServiceEntitlementsTest { private AuthorizationServiceImpl createSut(String... roles) throws EntitlementsException { List<GroupInfo> groupInfos = new ArrayList<>(); - for(String s : roles) { + for (String s : roles) { GroupInfo group = new GroupInfo(); group.setName(s); groupInfos.add(group); @@ -129,12 +129,9 @@ public class AuthorizationServiceEntitlementsTest { Groups output = new Groups(); output.setMemberEmail("akelham@bbc.com"); output.setGroups(groupInfos); - when(service.getGroups()).thenReturn(output); - return sut; } - } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/GsaAuthTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/GsaAuthTest.java index 077db3917a777340d9483ac7fe0621ba770a9fed..628e9f8339cc61073da9e9330a2baab95ad1e3d9 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/GsaAuthTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/GsaAuthTest.java @@ -36,19 +36,38 @@ import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) public class GsaAuthTest { + + private static final String GOOGLE_ID_TOKEN = "testHeader.testPayload.testSignature"; + private static Subscription gsa_subscription; + @Mock private IGoogleServiceAccount gsaTokenProvider; + @InjectMocks private GsaAuth sut; - private static Subscription gsa_subscription; - private static final String GOOGLE_ID_TOKEN = "testHeader.testPayload.testSignature"; - @BeforeClass public static void setup() { setGsa_subscription(); } + private static void setGsa_subscription() { + gsa_subscription = new Subscription(); + gsa_subscription.setName("gsa_test_subscription"); + gsa_subscription.setPushEndpoint("http:///gsa-challenge"); + gsa_subscription.setDescription("Description"); + gsa_subscription.setTopic("records-changed"); + gsa_subscription.setNotificationId("test-notification-id"); + gsa_subscription.setId("id_1"); + gsa_subscription.setCreatedBy("test@test.com"); + GsaSecret secret = new GsaSecret(); + GsaSecretValue value = new GsaSecretValue(); + value.setAudience("audience"); + value.setKey("{\"keyFile\":{\"key\":\"gsa\"}}"); + secret.setValue(value); + gsa_subscription.setSecret(secret); + } + @Test public void should_return_valid_EndpointAndHeaders_gsaClient() throws Exception { GsaSecret secret = (GsaSecret) gsa_subscription.getSecret(); @@ -71,21 +90,4 @@ public class GsaAuthTest { Assert.assertEquals(pushUrl, gsa_subscription.getPushEndpoint()); } - private static void setGsa_subscription() { - gsa_subscription = new Subscription(); - gsa_subscription.setName("gsa_test_subscription"); - gsa_subscription.setPushEndpoint("http:///gsa-challenge"); - gsa_subscription.setDescription("Description"); - gsa_subscription.setTopic("records-changed"); - gsa_subscription.setNotificationId("test-notification-id"); - gsa_subscription.setId("id_1"); - gsa_subscription.setCreatedBy("test@test.com"); - GsaSecret secret = new GsaSecret(); - GsaSecretValue value = new GsaSecretValue(); - value.setAudience("audience"); - value.setKey("{\"keyFile\":{\"key\":\"gsa\"}}"); - secret.setValue(value); - gsa_subscription.setSecret(secret); - } - } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/HmacAuthTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/HmacAuthTest.java index 130beb4d81c0392cb9896527b25bfbc347533709..406795fa388833faa95f120b55d6f8c576ae2baf 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/HmacAuthTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/HmacAuthTest.java @@ -34,19 +34,35 @@ import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) public class HmacAuthTest { + + private static final String SIGNED_SIGNATURE = "testEncodedInfo.testSignature"; + private static Subscription hmac_subscription; + @Mock private ISignatureService signatureService; + @InjectMocks private HmacAuth sut; - private static Subscription hmac_subscription; - private static final String SIGNED_SIGNATURE = "testEncodedInfo.testSignature"; - @BeforeClass public static void setup() { setHmac_subscription(); } + private static void setHmac_subscription() { + hmac_subscription = new Subscription(); + hmac_subscription.setName("hamc_test_subscription"); + hmac_subscription.setPushEndpoint("http://challenge"); + hmac_subscription.setDescription("Description"); + hmac_subscription.setTopic("records-changed"); + hmac_subscription.setNotificationId("test-notification-id"); + hmac_subscription.setId("id_1"); + hmac_subscription.setCreatedBy("test@test.com"); + HmacSecret secret = new HmacSecret(); + secret.setValue("testsecret"); + hmac_subscription.setSecret(secret); + } + @Test public void should_return_valid_EndpointAndHeaders() throws Exception { HmacSecret secret = (HmacSecret) hmac_subscription.getSecret(); @@ -67,18 +83,4 @@ public class HmacAuthTest { sut.getPushUrl(hmac_subscription.getPushEndpoint()); fail("should throw Exception"); } - - private static void setHmac_subscription() { - hmac_subscription = new Subscription(); - hmac_subscription.setName("hamc_test_subscription"); - hmac_subscription.setPushEndpoint("http://challenge"); - hmac_subscription.setDescription("Description"); - hmac_subscription.setTopic("records-changed"); - hmac_subscription.setNotificationId("test-notification-id"); - hmac_subscription.setId("id_1"); - hmac_subscription.setCreatedBy("test@test.com"); - HmacSecret secret = new HmacSecret(); - secret.setValue("testsecret"); - hmac_subscription.setSecret(secret); - } } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/auth/factory/AuthFactoryTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/factory/AuthFactoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5375c87c3ece41829ddc5fc94a8145cb7ca81ee9 --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/auth/factory/AuthFactoryTest.java @@ -0,0 +1,64 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.auth.factory; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.model.http.AppException; +import org.opengroup.osdu.notification.auth.GsaAuth; +import org.opengroup.osdu.notification.auth.HmacAuth; +import org.opengroup.osdu.notification.auth.interfaces.SecretAuth; + +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class AuthFactoryTest { + + @InjectMocks + AuthFactory authFactory; + + @Mock + private HmacAuth hmacAuth; + + @Mock + private GsaAuth gsaAuth; + + @Before + public void setup() { + MockitoAnnotations.initMocks(AuthFactoryTest.this); + } + + @Test(expected = AppException.class) + public void getSecretAuthTest_invalidType() { + authFactory.getSecretAuth("invalid"); + } + + @Test + public void getSecretAuthTest_gsaAuth() { + SecretAuth secretAuth = authFactory.getSecretAuth("GSA"); + assertTrue(secretAuth instanceof GsaAuth); + } + + @Test + public void getSecretAuthTest_hmacAuth() { + SecretAuth secretAuth = authFactory.getSecretAuth("HMAC"); + assertTrue(secretAuth instanceof HmacAuth); + } +} diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/di/CredentialHeadersProviderTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/di/CredentialHeadersProviderTest.java index f7bb0cc4e68d4a1726d24ea4dd3c0d8b6673e2a0..e7966e43b387cecb888a027c41d756d19ce9f8bf 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/di/CredentialHeadersProviderTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/di/CredentialHeadersProviderTest.java @@ -5,30 +5,60 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient; import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; -import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) +@RunWith(MockitoJUnitRunner.class) public class CredentialHeadersProviderTest { + @Mock private HttpServletRequest httpRequest; @Mock private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor; + @Mock + private IServiceAccountJwtClient serviceAccountJwtClient; + @InjectMocks private CredentialHeadersProvider headersProvider; + @Before + public void setup() { + MockitoAnnotations.initMocks(CredentialHeadersProviderTest.this); + } + @Test public void testGetIsOk() throws Exception { when(httpRequest.getMethod()).thenReturn(RequestMethod.GET.toString()); assertNotNull(headersProvider.getObject()); } + + @Test + public void getObject_patchTest() throws Exception { + when(httpRequest.getMethod()).thenReturn(RequestMethod.PATCH.toString()); + Map<String, String> mockAttributes = new HashMap<>(); + mockAttributes.put("data-partition-id", "opendes"); + when(pubsubRequestBodyExtractor.extractAttributesFromRequestBody()).thenReturn(mockAttributes); + when(serviceAccountJwtClient.getIdToken("opendes")).thenReturn("sampleAuthToken"); + + DpsHeaders dpsHeaders = headersProvider.getObject(); + assertNotNull(dpsHeaders); + assertEquals(dpsHeaders.getHeaders().get("content-type"), "application/json"); + assertEquals(dpsHeaders.getHeaders().get("authorization"), "sampleAuthToken"); + assertEquals(dpsHeaders.getHeaders().get("data-partition-id"), "opendes"); + } + } \ No newline at end of file diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java similarity index 60% rename from notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoTest.java rename to notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java index a0a7d4814d7c96e1bbe137188c7b28225fc8cd76..16e3f8c80c54d5ea0f55fba1be02854898fecf92 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java @@ -19,29 +19,44 @@ package org.opengroup.osdu.notification.di; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.opengroup.osdu.notification.provider.interfaces.IAppProperties; -import org.powermock.modules.junit4.PowerMockRunner; +import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; import javax.servlet.http.HttpServletRequest; -import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.when; -@RunWith(PowerMockRunner.class) -public class RequestInfoTest { +@RunWith(MockitoJUnitRunner.class) +public class RequestInfoExtTest { + + Map<String, String> httpHeaders; + + @Mock + DpsHeaders headers; + + @Mock + IPubsubRequestBodyExtractor requestBodyExtractor; + @Mock private IAppProperties config; + @Mock private HttpServletRequest http; + @Spy + @InjectMocks private RequestInfoExt sut; - Map<String, String> httpHeaders; - @Before public void setup() { httpHeaders = new HashMap<>(); @@ -49,18 +64,16 @@ public class RequestInfoTest { httpHeaders.put("correlation-id", "cor123"); httpHeaders.put("context", "67890"); httpHeaders.put("data-partition-id", "123"); - when(http.getMethod()).thenReturn("POST"); - when(http.getHeaderNames()).thenReturn(Collections.enumeration(httpHeaders.keySet())); - httpHeaders.forEach((k,v) -> when(http.getHeader(k)).thenReturn(v)); - sut = new RequestInfoExt(http); + MockitoAnnotations.initMocks(RequestInfoExtTest.this); } @Test - public void should_includeAllHeadersExcept_when_creatingHeaders() { - Map<String,String> map = this.sut.getHeaders().getHeaders(); - assertEquals("cor123", map.get("correlation-id")); - assertEquals("123", map.get("data-partition-id")); - assertEquals("aaa", map.get("authorization")); - assertEquals(null, map.get("context")); + public void assignPartitionIdIfNotInHeaderTest() { + when(http.getMethod()).thenReturn("POST"); + when(headers.getPartitionId()).thenReturn(null); + when(requestBodyExtractor.extractAttributesFromRequestBody()).thenReturn(httpHeaders); + this.sut.assignPartitionIdIfNotInHeader(); + verify(requestBodyExtractor, times(1)).extractAttributesFromRequestBody(); } + } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/di/SubscriptionCacheFactoryTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/di/SubscriptionCacheFactoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..893e635020565ab2e8d9a906de6742c055ffa210 --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/di/SubscriptionCacheFactoryTest.java @@ -0,0 +1,77 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.di; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.common.model.tenant.TenantInfo; +import org.opengroup.osdu.core.common.multitenancy.PartitionTenantInfoFactory; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SubscriptionCacheFactoryTest { + + SubscriptionCacheFactory subscriptionCacheFactory; + + @Mock + private DpsHeaders headers; + + @Mock + private PartitionTenantInfoFactory tenantFactory; + + @Mock + private TenantInfo tenantInfo; + + @Before + public void setup() { + subscriptionCacheFactory = new SubscriptionCacheFactory(1234567, 1000); + MockitoAnnotations.initMocks(SubscriptionCacheFactoryTest.this); + ReflectionTestUtils.setField(subscriptionCacheFactory, "headers", headers); + ReflectionTestUtils.setField(subscriptionCacheFactory, "tenantFactory", tenantFactory); + tenantInfo.setDataPartitionId("opendes"); + when(tenantFactory.getTenantInfo(any())).thenReturn(tenantInfo); + when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn("opendes"); + when(tenantInfo.getDataPartitionId()).thenReturn("opendes"); + subscriptionCacheFactory.put("testKey", "testVal"); + } + + @Test + public void getTest() { + String actual = subscriptionCacheFactory.get("testKey"); + assertEquals("testVal", actual); + } + + @Test + public void deleteTest() { + subscriptionCacheFactory.delete("testKey"); + assertNull(subscriptionCacheFactory.get("testKey")); + } + + @Test + public void clearAll() { + subscriptionCacheFactory.clearAll(); + assertNull(subscriptionCacheFactory.get("testKey")); + } +} \ No newline at end of file diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/errors/SpringExceptionMapperTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/errors/SpringExceptionMapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..718055c61368c6908a9dc2eac56ed9c65a285f13 --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/errors/SpringExceptionMapperTest.java @@ -0,0 +1,127 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.errors; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.AppError; +import org.opengroup.osdu.core.common.model.http.AppException; +import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.WebRequest; + +import javax.servlet.http.HttpServletRequest; +import javax.xml.bind.ValidationException; +import java.io.IOException; +import java.nio.file.AccessDeniedException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(MockitoJUnitRunner.class) +public class SpringExceptionMapperTest { + + @InjectMocks + private SpringExceptionMapper springExceptionMapper; + + @Mock + private JaxRsDpsLog log; + + @Mock + private HttpServletRequest servletRequest; + + @Mock + private WebRequest request; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(SpringExceptionMapperTest.this); + } + + @Test + public void handleAppException() { + AppException appException = new AppException(400, "Sample app exception reason", "Sample app exception message"); + appException.setOriginalException(new NullPointerException()); + ResponseEntity<Object> actual = springExceptionMapper.handleAppException(appException); + AppError appError = (AppError) actual.getBody(); + + assertNotNull(actual); + assertEquals(400, Objects.requireNonNull(appError).getCode()); + assertEquals("Sample app exception reason", appError.getReason()); + assertEquals("Sample app exception message", appError.getMessage()); + } + + @Test + public void handleValidationException() { + ValidationException validationException = new ValidationException("Sample Validation Exception"); + ResponseEntity<Object> actual = springExceptionMapper.handleValidationException(validationException); + AppError appError = (AppError) actual.getBody(); + + assertNotNull(actual); + assertEquals(400, appError.getCode()); + assertEquals("Sample Validation Exception", appError.getMessage()); + assertEquals("Bad request", appError.getReason()); + } + + @Test + public void handleAccessDeniedException() { + AccessDeniedException accessDeniedException = new AccessDeniedException("Sample Access Denied Exception"); + ResponseEntity<Object> actual = springExceptionMapper.handleAccessDeniedException(accessDeniedException, request); + AppError appError = (AppError) actual.getBody(); + + assertNotNull(actual); + assertEquals(401, appError.getCode()); + assertEquals("Sample Access Denied Exception", appError.getMessage()); + assertEquals("Unauthorized", appError.getReason()); + } + + @Test + public void handleGeneralException() { + Exception exception = new Exception("A General Exception"); + ResponseEntity<Object> actual = springExceptionMapper.handleGeneralException(exception); + AppError appError = (AppError) actual.getBody(); + + assertNotNull(appError); + assertEquals(500, appError.getCode()); + assertEquals("An unknown error has occurred.", appError.getMessage()); + assertEquals("Server Error", appError.getReason()); + } + + @Test + public void handleIOException_connectionClosed() { + IOException ioException = new IOException("Sample IO Exception due to broken pipe"); + ResponseEntity<Object> actual = springExceptionMapper.handleIOException(ioException); + + assertEquals(actual, null); + } + + @Test + public void handleIOExceptionTest() { + IOException ioException = new IOException("Sample IO Exception"); + ResponseEntity<Object> actual = springExceptionMapper.handleIOException(ioException); + AppError appError = (AppError) actual.getBody(); + + assertNotNull(actual); + assertEquals("Unknown error", appError.getReason()); + assertEquals("Sample IO Exception", appError.getMessage()); + assertEquals(503, appError.getCode()); + } +} \ No newline at end of file diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/logging/ResponseLogFilterTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/logging/ResponseLogFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..945ef7fda025ee39b27e46ed2a241549a5f2115a --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/logging/ResponseLogFilterTest.java @@ -0,0 +1,84 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.logging; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.logging.ILogger; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.common.model.http.Request; +import org.opengroup.osdu.notification.di.RequestInfoExt; + +import javax.servlet.FilterChain; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ResponseLogFilterTest { + + @InjectMocks + ResponseLogFilter responseLogFilter; + + @Mock + private RequestInfoExt requestInfoExt; + + @Mock + private ILogger logger; + + @Mock + private FilterChain filterChain; + + @Mock + private ServletContext servletContext; + + @Mock + private HttpServletRequest servletRequest; + + @Mock + private HttpServletResponse servletResponse; + + @Spy + private DpsHeaders dpsHeaders; + + @Before + public void setup() throws ServletException, IOException { + MockitoAnnotations.initMocks(ResponseLogFilterTest.this); + when(servletRequest.getServletContext()).thenReturn(servletContext); + } + + @Test + public void doFilterTest() throws ServletException, IOException { + when(requestInfoExt.getHeaders()).thenReturn(dpsHeaders); + when(servletRequest.getMethod()).thenReturn("OPTIONS"); + responseLogFilter.doFilter(servletRequest, servletResponse, filterChain); + verify(logger, times(1)).request(eq("notification.request"), any(Request.class), anyMap()); + } +} diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTests.java b/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java similarity index 77% rename from notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTests.java rename to notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java index 0c5f8636d7e9c9d2d3c4fc8ea652372524361415..3336ef1f2989c40ae27be95682b0ba33e91ae401 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTests.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java @@ -16,93 +16,64 @@ package org.opengroup.osdu.notification.service; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import org.opengroup.osdu.core.common.http.HttpClient; import org.opengroup.osdu.core.common.http.HttpResponse; import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; -import org.opengroup.osdu.core.common.model.notification.*; +import org.opengroup.osdu.core.common.model.notification.GsaSecret; +import org.opengroup.osdu.core.common.model.notification.GsaSecretValue; +import org.opengroup.osdu.core.common.model.notification.HmacSecret; +import org.opengroup.osdu.core.common.model.notification.Subscription; import org.opengroup.osdu.core.common.notification.SubscriptionException; import org.opengroup.osdu.notification.auth.factory.AuthFactory; import org.opengroup.osdu.notification.auth.interfaces.SecretAuth; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.Map; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) -public class NotificationHandlerTests { +@RunWith(MockitoJUnitRunner.class) +public class NotificationHandlerTest { + + private static final String NOTIFICATION_ID = "test-notification-id"; + private static final String PUBSUB_MESSAGE = "test-pubsub-message-data"; + private static Subscription gsa_subscription; + private static Subscription hmac_subscription; + private final HttpResponse response = new HttpResponse(); + @Mock private SubscriptionHandler subscriptionHandler; + @Mock private AuthFactory authFactory; + @Mock private SecretAuth secretAuth; + @Mock private HttpClient httpClient; + @Mock private JaxRsDpsLog log; + @InjectMocks private NotificationHandler sut; - private HttpResponse response = new HttpResponse(); - private static final String NOTIFICATION_ID = "test-notification-id"; - private static final String PUBSUB_MESSAGE = "test-pubsub-message-data"; - private static Subscription gsa_subscription; - private static Subscription hmac_subscription; - @BeforeClass public static void setup() { setHmac_subscription(); setGsa_subscription(); } - @Test - public void should_return200_whenPubsubMessageValidAndSuccessCodeReturnedFromClient_gsa() throws Exception { - response.setResponseCode(200); - Map<String, String> headers = new HashMap<String, String>(); - when(this.subscriptionHandler.getSubscriptionFromCache(this.NOTIFICATION_ID)).thenReturn(gsa_subscription); - when(this.authFactory.getSecretAuth(any())).thenReturn(secretAuth); - when(this.httpClient.send(any())).thenReturn(response); - when(this.secretAuth.getPushUrl(gsa_subscription.getPushEndpoint())).thenReturn(gsa_subscription.getPushEndpoint()); - when(this.secretAuth.getRequestHeaders()).thenReturn(headers); - HttpResponse response = this.sut.notifySubscriber(this.NOTIFICATION_ID, this.PUBSUB_MESSAGE, headers); - Assert.assertEquals(200, response.getResponseCode()); - } - - @Test - public void should_return200_whenPubsubMessageValidAndSuccessCodeReturnedFromClient_hmac() throws Exception { - response.setResponseCode(200); - Map<String, String> headers = new HashMap<String, String>(); - when(this.subscriptionHandler.getSubscriptionFromCache(this.NOTIFICATION_ID)).thenReturn(hmac_subscription); - when(this.authFactory.getSecretAuth(any())).thenReturn(secretAuth); - when(this.httpClient.send(any())).thenReturn(response); - when(this.secretAuth.getPushUrl(hmac_subscription.getPushEndpoint())).thenReturn(hmac_subscription.getPushEndpoint()); - when(this.secretAuth.getRequestHeaders()).thenReturn(headers); - HttpResponse response = this.sut.notifySubscriber(this.NOTIFICATION_ID, this.PUBSUB_MESSAGE, headers); - Assert.assertEquals(200, response.getResponseCode()); - } - - @Test(expected = SubscriptionException.class) - public void should_throwException_whenSubscriptionHandlerThrowsException() throws Exception { - Map<String, String> headers = new HashMap<String, String>(); - when(this.authFactory.getSecretAuth(any())).thenReturn(secretAuth); - when(this.httpClient.send(any())).thenReturn(response); - when(this.secretAuth.getPushUrl(gsa_subscription.getPushEndpoint())).thenReturn(gsa_subscription.getPushEndpoint()); - when(this.secretAuth.getRequestHeaders()).thenReturn(headers); - when(subscriptionHandler.getSubscriptionFromCache(this.NOTIFICATION_ID)).thenThrow(new SubscriptionException("error", response)); - this.sut.notifySubscriber(this.NOTIFICATION_ID, this.PUBSUB_MESSAGE, headers); - fail("should throw SubscriptionException"); - } - private static void setGsa_subscription() { gsa_subscription = new Subscription(); gsa_subscription.setName("gsa_test_subscription"); @@ -118,7 +89,6 @@ public class NotificationHandlerTests { value.setKey("keyFile"); secret.setValue(value); gsa_subscription.setSecret(secret); - } private static void setHmac_subscription() { @@ -134,4 +104,38 @@ public class NotificationHandlerTests { secret.setValue("testsecret"); hmac_subscription.setSecret(secret); } + + @Test + public void should_return200_whenPubsubMessageValidAndSuccessCodeReturnedFromClient_gsa() throws Exception { + response.setResponseCode(200); + Map<String, String> headers = new HashMap<String, String>(); + when(this.subscriptionHandler.getSubscriptionFromCache(NOTIFICATION_ID)).thenReturn(gsa_subscription); + when(this.authFactory.getSecretAuth(any())).thenReturn(secretAuth); + when(this.httpClient.send(any())).thenReturn(response); + when(this.secretAuth.getPushUrl(gsa_subscription.getPushEndpoint())).thenReturn(gsa_subscription.getPushEndpoint()); + when(this.secretAuth.getRequestHeaders()).thenReturn(headers); + HttpResponse response = this.sut.notifySubscriber(NOTIFICATION_ID, PUBSUB_MESSAGE, headers); + assertEquals(200, response.getResponseCode()); + } + + @Test + public void should_return200_whenPubsubMessageValidAndSuccessCodeReturnedFromClient_hmac() throws Exception { + response.setResponseCode(200); + Map<String, String> headers = new HashMap<String, String>(); + when(this.subscriptionHandler.getSubscriptionFromCache(NOTIFICATION_ID)).thenReturn(hmac_subscription); + when(this.authFactory.getSecretAuth(any())).thenReturn(secretAuth); + when(this.httpClient.send(any())).thenReturn(response); + when(this.secretAuth.getPushUrl(hmac_subscription.getPushEndpoint())).thenReturn(hmac_subscription.getPushEndpoint()); + when(this.secretAuth.getRequestHeaders()).thenReturn(headers); + HttpResponse response = this.sut.notifySubscriber(NOTIFICATION_ID, PUBSUB_MESSAGE, headers); + assertEquals(200, response.getResponseCode()); + } + + @Test(expected = SubscriptionException.class) + public void should_throwException_whenSubscriptionHandlerThrowsException() throws Exception { + Map<String, String> headers = new HashMap<String, String>(); + when(subscriptionHandler.getSubscriptionFromCache(NOTIFICATION_ID)).thenThrow(new SubscriptionException("error", response)); + this.sut.notifySubscriber(NOTIFICATION_ID, PUBSUB_MESSAGE, headers); + fail("should throw SubscriptionException"); + } } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTests.java b/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java similarity index 75% rename from notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTests.java rename to notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java index aefb8b62c74d2a68000f07e2b713b085c0ebbc6a..f90a0cf904709b69a504dc439c63c1a9d07ff502 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTests.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java @@ -22,41 +22,41 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import org.opengroup.osdu.core.common.http.HttpResponse; -import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; import org.opengroup.osdu.core.common.model.http.AppException; -import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.opengroup.osdu.core.common.model.notification.Subscription; import org.opengroup.osdu.core.common.notification.ISubscriptionFactory; import org.opengroup.osdu.core.common.notification.ISubscriptionService; import org.opengroup.osdu.core.common.notification.SubscriptionException; import org.opengroup.osdu.core.common.notification.SubscriptionService; import org.opengroup.osdu.notification.di.SubscriptionCacheFactory; -import org.powermock.modules.junit4.PowerMockRunner; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) -public class SubscriptionHandlerTests { +@RunWith(MockitoJUnitRunner.class) +public class SubscriptionHandlerTest { + + private static final String NOTIFICATION_ID = "test-notification-id"; + @Mock private ISubscriptionFactory subscriptionFactory; + @Mock private SubscriptionCacheFactory subscriptionCacheFactory; + @Mock private ObjectMapper objectMapper; + @InjectMocks private SubscriptionHandler sut; - private static final String NOTIFICATION_ID = "test-notification-id"; - @Test(expected = AppException.class) public void should_throwException_whenSubscriptionNotFound() throws Exception { when(this.subscriptionCacheFactory.get(any())).thenReturn(null); @@ -64,23 +64,6 @@ public class SubscriptionHandlerTests { when(this.subscriptionFactory.create(any())).thenReturn(subscriptionService); HttpResponse response = new HttpResponse(); when(subscriptionService.query(any())).thenThrow(new SubscriptionException("error", response)); - this.sut.getSubscriptionFromCache(this.NOTIFICATION_ID); - fail("should throw AppException"); - } - - @Test(expected = AppException.class) - public void should_throwException_whenSubscriptionParsingErrorOccurs() throws Exception { - when(this.subscriptionCacheFactory.get(any())).thenReturn(null); - ISubscriptionService subscriptionService = mock(SubscriptionService.class); - when(this.subscriptionFactory.create(any())).thenReturn(subscriptionService); - String jsonSubscription = this.getHmacSubscription(); - ObjectMapper objectMapper = new ObjectMapper(); - Subscription subscription = objectMapper.readValue(jsonSubscription, Subscription.class); - List<Subscription> queryResult = new ArrayList<>(); - queryResult.add(subscription); - when(subscriptionService.query(any())).thenReturn(queryResult); - sut.setObjectMapper(this.objectMapper); - when(this.objectMapper.readValue(anyString(), any(Class.class))).thenThrow(new IOException()); this.sut.getSubscriptionFromCache(NOTIFICATION_ID); fail("should throw AppException"); } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/swagger/HomeControllerTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/swagger/HomeControllerTest.java index 6bd3e8084d58fd9a779c75d74f887b3901d0b349..895cf1ab27cad997e0510d6c28b1bd89f1c5c55b 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/swagger/HomeControllerTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/swagger/HomeControllerTest.java @@ -2,6 +2,8 @@ package org.opengroup.osdu.notification.swagger; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; @@ -9,6 +11,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; +@RunWith(MockitoJUnitRunner.class) public class HomeControllerTest { private MockMvc mockMvc; diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/utils/NotificationFilterTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/utils/NotificationFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ae67d0617d868da34cb3a0d6b059682d67b394bb --- /dev/null +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/utils/NotificationFilterTest.java @@ -0,0 +1,70 @@ +// Copyright © Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package org.opengroup.osdu.notification.utils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; + +@RunWith(MockitoJUnitRunner.class) +public class NotificationFilterTest { + + @InjectMocks + private NotificationFilter notificationFilter; + + @Spy + private DpsHeaders dpsHeaders; + + @Mock + private FilterChain filterChain; + + @Mock + private HttpServletRequest servletRequest; + + @Mock + private HttpServletResponse servletResponse; + + @Before + public void setup() throws ServletException, IOException { + MockitoAnnotations.initMocks(NotificationFilterTest.this); + doNothing().when(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); + } + + @Test + public void doFilterTest() throws ServletException, IOException { + notificationFilter.doFilter(servletRequest, servletResponse, filterChain); + assertNotNull(dpsHeaders.getHeaders().get("correlation-id")); + assertEquals(dpsHeaders.getHeaders().get("content-type"), "application/json"); + } +} \ No newline at end of file