From b2ac114782bd950c4d5fa67e2345886f8d613043 Mon Sep 17 00:00:00 2001 From: SmithaManjunath <smanjunath@microsoft.com> Date: Thu, 31 Mar 2022 09:33:51 +0530 Subject: [PATCH] increase code coverage of notification-core to 80% --- .../api/GlobalErrorControllerTest.java | 33 ++++--- .../osdu/notification/api/InfoApiTest.java | 56 ++++++------ .../notification/api/PubsubEndpointTest.java | 12 +-- .../auth/AuthorizationFilterTest.java | 2 +- .../AuthorizationServiceEntitlementsTest.java | 34 ++++---- .../osdu/notification/auth/GsaAuthTest.java | 39 ++++----- .../osdu/notification/auth/HmacAuthTest.java | 33 ++++--- .../auth/factory/AuthFactoryTest.java | 16 ++-- .../di/CredentialHeadersProviderTest.java | 17 ++-- .../notification/di/RequestInfoExtTest.java | 25 ++---- .../di/SubscriptionCacheFactoryTest.java | 23 ++--- .../errors/SpringExceptionMapperTest.java | 37 +++----- .../logging/ResponseLogFilterTest.java | 9 +- .../service/NotificationHandlerTest.java | 87 ++++++++++--------- .../service/SubscriptionHandlerTest.java | 10 +-- .../utils/NotificationFilterTest.java | 2 - 16 files changed, 191 insertions(+), 244 deletions(-) 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 index ebc203c7f..8a4ff8663 100644 --- 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 @@ -10,66 +10,65 @@ import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class GlobalErrorControllerTest { - @InjectMocks - private GlobalErrorController globalErrorController; - @Mock HttpServletRequest httpServletRequest; + @InjectMocks + private GlobalErrorController globalErrorController; @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(GlobalErrorControllerTest.this); when(httpServletRequest.getAttribute(eq("javax.servlet.error.exception"))).thenReturn(new Exception("sample exception")); } @Test - public void handleErrorGetTest(){ + 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\" }"); + String expected = globalErrorController.handleErrorGet(httpServletRequest); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); } @Test - public void handleErrorPutTest(){ + 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\" }"); + assertEquals(expected, "{\"code\": 404, \"reason:\": \"Not Found\" \"message\":\"sample exception\" }"); } @Test - public void handleErrorPatchTest(){ + 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\" }"); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); } @Test - public void handleErrorDeleteTest(){ + 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\" }"); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); } @Test - public void handleErrorPostTest(){ + 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\" }"); + assertEquals(expected, "{\"code\": 500, \"reason:\": \"Internal Server Error\" \"message\":\"An unknown error has occurred\" }"); } @Test public void getErrorPathTest() { - assertEquals(globalErrorController.getErrorPath(),"/error"); + assertEquals(globalErrorController.getErrorPath(), "/error"); } 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 1b694967b..58f021b44 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/PubsubEndpointTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java index 6d48f12e9..de0af9ef8 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/api/PubsubEndpointTest.java @@ -25,22 +25,19 @@ 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 PubsubEndpointTest { + private static final String NOTIFICATION_ID = "test-notification-id"; + private static final String PUBSUB_MESSAGE = "test-pubsub-message-data"; @Mock private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor; @Mock @@ -49,10 +46,7 @@ public class PubsubEndpointTest { 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(); + private final HttpResponse response = new HttpResponse(); @Before public void setup() throws Exception { 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 61f052080..485acc74b 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; 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 cd9a70007..529de0881 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; @@ -56,12 +56,12 @@ public class AuthorizationServiceEntitlementsTest { 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_ussrHasPermission() throws EntitlementsException { sut = createSut("service.register.user"); AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user"); @@ -70,7 +70,7 @@ public class AuthorizationServiceEntitlementsTest { } @Test - public void should_returnUser_when_ussrHasAnyPermission()throws EntitlementsException { + public void should_returnUser_when_ussrHasAnyPermission() throws EntitlementsException { sut = createSut("service.register.editor"); AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user", "service.register.editor"); @@ -79,19 +79,19 @@ public class AuthorizationServiceEntitlementsTest { } @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); 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 077db3917..803fe3f54 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,35 @@ 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 +87,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 130beb4d8..06ae5e765 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,32 @@ 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 +80,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 index ce74940ec..5c00336e8 100644 --- 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 @@ -7,46 +7,42 @@ 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.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.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(MockitoJUnitRunner.class) public class AuthFactoryTest { + @InjectMocks + AuthFactory authFactory; @Mock private HmacAuth hmacAuth; - @Mock private GsaAuth gsaAuth; - @InjectMocks - AuthFactory authFactory; - @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(AuthFactoryTest.this); } @Test(expected = AppException.class) - public void getSecretAuthTest_invalidType(){ + public void getSecretAuthTest_invalidType() { authFactory.getSecretAuth("invalid"); } @Test - public void getSecretAuthTest_gsaAuth(){ + public void getSecretAuthTest_gsaAuth() { SecretAuth secretAuth = authFactory.getSecretAuth("GSA"); assertTrue(secretAuth instanceof GsaAuth); } @Test - public void getSecretAuthTest_hmacAuth(){ + 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 d2b3f74b5..e7788440a 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 @@ -10,15 +10,14 @@ 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(MockitoJUnitRunner.class) @@ -36,7 +35,7 @@ public class CredentialHeadersProviderTest { private CredentialHeadersProvider headersProvider; @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(CredentialHeadersProviderTest.this); } @@ -49,16 +48,16 @@ public class CredentialHeadersProviderTest { @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"); + 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(headersProvider.getObject()); - assertEquals(dpsHeaders.getHeaders().get("content-type"),"application/json"); - assertEquals(dpsHeaders.getHeaders().get("authorization"),"sampleAuthToken"); - assertEquals(dpsHeaders.getHeaders().get("data-partition-id"),"opendes"); + assertEquals(dpsHeaders.getHeaders().get("content-type"), "application/json"); + assertEquals(dpsHeaders.getHeaders().get("authorization"), "sampleAuthToken"); + assertEquals(dpsHeaders.getHeaders().get("data-partition-id"), "opendes"); } diff --git a/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java index a9ff1953b..366bb5a9a 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/di/RequestInfoExtTest.java @@ -24,44 +24,33 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.opengroup.osdu.core.common.http.RequestBodyExtractor; import org.opengroup.osdu.core.common.model.http.DpsHeaders; import org.opengroup.osdu.notification.provider.interfaces.IAppProperties; import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.bind.annotation.RequestMethod; 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.verifyNew; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(MockitoJUnitRunner.class) public class RequestInfoExtTest { - @Mock - private IAppProperties config; - @Mock - private HttpServletRequest http; - @Mock DpsHeaders headers; - @Mock IPubsubRequestBodyExtractor requestBodyExtractor; - + Map<String, String> httpHeaders; + @Mock + private IAppProperties config; + @Mock + private HttpServletRequest http; @Spy @InjectMocks private RequestInfoExt sut; - Map<String, String> httpHeaders; - @Before public void setup() { httpHeaders = new HashMap<>(); @@ -74,13 +63,13 @@ public class RequestInfoExtTest { @Test - public void assignPartitionIdIfNotInHeaderTest(){ + 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(); + 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 index 5957ce446..8b17bbec2 100644 --- 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 @@ -3,23 +3,17 @@ 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.cache.ICache; -import org.opengroup.osdu.core.common.cache.MultiTenantCache; -import org.opengroup.osdu.core.common.cache.RedisCache; 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.opengroup.osdu.core.common.provider.interfaces.ITenantFactory; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -38,26 +32,25 @@ public class SubscriptionCacheFactoryTest { @Before - public void setup(){ - subscriptionCacheFactory = new SubscriptionCacheFactory(1234567,1000); + public void setup() { + subscriptionCacheFactory = new SubscriptionCacheFactory(1234567, 1000); MockitoAnnotations.initMocks(SubscriptionCacheFactoryTest.this); - ReflectionTestUtils.setField(subscriptionCacheFactory,"headers",headers); - ReflectionTestUtils.setField(subscriptionCacheFactory,"tenantFactory",tenantFactory); + 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"); + subscriptionCacheFactory.put("testKey", "testVal"); } - @Test public void getTest() { String actual = subscriptionCacheFactory.get("testKey"); - assertEquals("testVal",actual); + assertEquals("testVal", actual); } @Test 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 index 16b1b1682..8594ff84d 100644 --- 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 @@ -1,6 +1,5 @@ package org.opengroup.osdu.notification.errors; -import org.checkerframework.checker.units.qual.A; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,14 +10,7 @@ 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.core.MethodParameter; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.validation.BindException; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; @@ -69,10 +61,9 @@ public class SpringExceptionMapperTest { ResponseEntity<Object> actual = springExceptionMapper.handleValidationException(validationException); assertNotNull(actual); AppError appError = (AppError) actual.getBody(); - assertEquals(400,appError.getCode()); - assertEquals("Sample Validation Exception",appError.getMessage()); - assertEquals("Bad request",appError.getReason()); - + assertEquals(400, appError.getCode()); + assertEquals("Sample Validation Exception", appError.getMessage()); + assertEquals("Bad request", appError.getReason()); } @@ -80,12 +71,12 @@ public class SpringExceptionMapperTest { @Test public void handleAccessDeniedException() { AccessDeniedException accessDeniedException = new AccessDeniedException("Sample Access Denied Exception"); - ResponseEntity<Object> actual = springExceptionMapper.handleAccessDeniedException(accessDeniedException,request); + ResponseEntity<Object> actual = springExceptionMapper.handleAccessDeniedException(accessDeniedException, request); assertNotNull(actual); AppError appError = (AppError) actual.getBody(); - assertEquals(401,appError.getCode()); - assertEquals("Sample Access Denied Exception",appError.getMessage()); - assertEquals("Unauthorized",appError.getReason()); + assertEquals(401, appError.getCode()); + assertEquals("Sample Access Denied Exception", appError.getMessage()); + assertEquals("Unauthorized", appError.getReason()); } @@ -95,9 +86,9 @@ public class SpringExceptionMapperTest { 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()); + assertEquals(500, appError.getCode()); + assertEquals("An unknown error has occurred.", appError.getMessage()); + assertEquals("Server Error", appError.getReason()); } @@ -106,7 +97,7 @@ public class SpringExceptionMapperTest { public void handleIOException_connectionClosed() { IOException ioException = new IOException("Sample IO Exception due to broken pipe"); ResponseEntity<Object> actual = springExceptionMapper.handleIOException(ioException); - assertEquals(actual,null); + assertEquals(actual, null); } @@ -116,9 +107,9 @@ public class SpringExceptionMapperTest { ResponseEntity<Object> actual = springExceptionMapper.handleIOException(ioException); assertNotNull(actual); AppError appError = (AppError) actual.getBody(); - assertEquals("Unknown error",appError.getReason()); - assertEquals("Sample IO Exception",appError.getMessage()); - assertEquals(503,appError.getCode()); + 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 index abd30fccd..b9c79256c 100644 --- 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 @@ -16,18 +16,13 @@ import org.opengroup.osdu.notification.di.RequestInfoExt; import javax.servlet.FilterChain; import javax.servlet.ServletContext; 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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -69,8 +64,8 @@ public class ResponseLogFilterTest { 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()); + 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/NotificationHandlerTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java index 1b86f2aaa..38c6e32ec 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/service/NotificationHandlerTest.java @@ -26,11 +26,13 @@ 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; @@ -41,6 +43,10 @@ import static org.mockito.Mockito.when; @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; @Mock private SubscriptionHandler subscriptionHandler; @Mock @@ -53,12 +59,7 @@ public class NotificationHandlerTest { 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; + private final HttpResponse response = new HttpResponse(); @BeforeClass public static void setup() { @@ -66,41 +67,6 @@ public class NotificationHandlerTest { 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(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"); @@ -132,4 +98,39 @@ public class NotificationHandlerTest { 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); + 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(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); + 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(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/SubscriptionHandlerTest.java b/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java index 118d76565..ff1be1785 100644 --- a/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java +++ b/notification-core/src/test/java/org/opengroup/osdu/notification/service/SubscriptionHandlerTest.java @@ -24,29 +24,25 @@ 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(MockitoJUnitRunner.class) public class SubscriptionHandlerTest { + private static final String NOTIFICATION_ID = "test-notification-id"; @Mock private ISubscriptionFactory subscriptionFactory; @Mock @@ -56,8 +52,6 @@ public class SubscriptionHandlerTest { @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); @@ -65,7 +59,7 @@ public class SubscriptionHandlerTest { 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); + this.sut.getSubscriptionFromCache(NOTIFICATION_ID); fail("should throw AppException"); } 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 index 07297baa9..46ce614d8 100644 --- 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 @@ -16,7 +16,6 @@ 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.assertNotNull; @@ -42,7 +41,6 @@ public class NotificationFilterTest { private HttpServletResponse servletResponse; - @Before public void setup() throws ServletException, IOException { MockitoAnnotations.initMocks(NotificationFilterTest.this); -- GitLab