Skip to content
Snippets Groups Projects
Commit 68380fde authored by Smitha Manjunath's avatar Smitha Manjunath
Browse files

Merge branch 'smanjunath/increaseCodeCoverage' into 'master'

Increase code coverage of Core module to 80%

See merge request !203
parents b038451f 5761be49
No related branches found
No related tags found
3 merge requests!232Update os-core-lib-azure,!231initial commit,!203Increase code coverage of Core module to 80%
Pipeline #108625 failed
Showing
with 769 additions and 205 deletions
...@@ -290,27 +290,45 @@ ...@@ -290,27 +290,45 @@
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.2</version> <version>0.8.2</version>
<configuration>
<excludes>
<exclude>**/models/*</exclude>
<exclude>**/swagger/*</exclude>
</excludes>
</configuration>
<executions> <executions>
<execution> <execution>
<id>prepare-unit-tests</id> <id>default-prepare-agent</id>
<goals> <goals>
<goal>prepare-agent</goal> <goal>prepare-agent</goal>
</goals> </goals>
</execution> </execution>
<!-- prepare agent for measuring integration tests -->
<execution> <execution>
<id>prepare-agent</id> <id>report</id>
<phase>prepare-package</phase>
<goals> <goals>
<goal>prepare-agent</goal> <goal>report</goal>
</goals> </goals>
<phase>pre-integration-test</phase>
<configuration>
<propertyName>itCoverageAgent</propertyName>
</configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </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> </project>
// 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
...@@ -17,11 +17,6 @@ ...@@ -17,11 +17,6 @@
package org.opengroup.osdu.notification.api; 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.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -32,33 +27,38 @@ import org.mockito.junit.MockitoJUnitRunner; ...@@ -32,33 +27,38 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.info.VersionInfoBuilder; import org.opengroup.osdu.core.common.info.VersionInfoBuilder;
import org.opengroup.osdu.core.common.model.info.VersionInfo; 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) @RunWith(MockitoJUnitRunner.class)
public class InfoApiTest { public class InfoApiTest {
@InjectMocks @InjectMocks
private InfoApi sut; private InfoApi sut;
@Mock @Mock
private VersionInfoBuilder versionInfoBuilder; private VersionInfoBuilder versionInfoBuilder;
@Before @Before
public void setup(){ public void setup() {
MockitoAnnotations.initMocks(InfoApiTest.this); MockitoAnnotations.initMocks(InfoApiTest.this);
} }
@Test @Test
public void should_return200_getVersionInfo() throws IOException { public void should_return200_getVersionInfo() throws IOException {
VersionInfo versionInfo = VersionInfo.builder() VersionInfo versionInfo = VersionInfo.builder()
.groupId("group") .groupId("group")
.artifactId("artifact") .artifactId("artifact")
.version("0.1.0") .version("0.1.0")
.buildTime("1000") .buildTime("1000")
.branch("master") .branch("master")
.commitId("7777") .commitId("7777")
.commitMessage("Merge commit") .commitMessage("Merge commit")
.build(); .build();
when(versionInfoBuilder.buildVersionInfo()).thenReturn(versionInfo); when(versionInfoBuilder.buildVersionInfo()).thenReturn(versionInfo);
VersionInfo response = this.sut.info(); VersionInfo response = this.sut.info();
assertEquals(versionInfo, response); assertEquals(versionInfo, response);
} }
} }
...@@ -25,35 +25,34 @@ import org.mockito.Mock; ...@@ -25,35 +25,34 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.http.HttpResponse; import org.opengroup.osdu.core.common.http.HttpResponse;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; 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.provider.interfaces.IPubsubRequestBodyExtractor;
import org.opengroup.osdu.notification.service.NotificationHandler; import org.opengroup.osdu.notification.service.NotificationHandler;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import java.util.HashMap; import java.util.HashMap;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @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 @Mock
private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor; private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor;
@Mock @Mock
private NotificationHandler notificationHandler; private NotificationHandler notificationHandler;
@Mock @Mock
private JaxRsDpsLog log; private JaxRsDpsLog log;
@InjectMocks @InjectMocks
private PubsubEndpoint sut; 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 @Before
public void setup() throws Exception { public void setup() throws Exception {
when(this.pubsubRequestBodyExtractor.extractNotificationIdFromRequestBody()).thenReturn(NOTIFICATION_ID); when(this.pubsubRequestBodyExtractor.extractNotificationIdFromRequestBody()).thenReturn(NOTIFICATION_ID);
......
...@@ -27,8 +27,8 @@ import org.opengroup.osdu.core.common.model.http.DpsHeaders; ...@@ -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.core.common.provider.interfaces.IAuthorizationService;
import org.opengroup.osdu.notification.di.RequestInfoExt; import org.opengroup.osdu.notification.di.RequestInfoExt;
import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; 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.provider.interfaces.IServiceAccountValidator;
import org.opengroup.osdu.notification.utils.Config;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -53,16 +53,22 @@ public class AuthorizationFilterTest { ...@@ -53,16 +53,22 @@ public class AuthorizationFilterTest {
@Mock @Mock
private DpsHeaders headers; private DpsHeaders headers;
@Mock @Mock
private HttpServletRequest request; private HttpServletRequest request;
@Mock @Mock
private RequestInfoExt requestInfo; private RequestInfoExt requestInfo;
@Mock @Mock
private IAuthorizationService authorizationService; private IAuthorizationService authorizationService;
@Mock @Mock
private IServiceAccountValidator validator; private IServiceAccountValidator validator;
@Mock @Mock
private IPubsubRequestBodyExtractor extractor; private IPubsubRequestBodyExtractor extractor;
@InjectMocks @InjectMocks
private AuthorizationFilter sut; private AuthorizationFilter sut;
...@@ -87,7 +93,6 @@ public class AuthorizationFilterTest { ...@@ -87,7 +93,6 @@ public class AuthorizationFilterTest {
public void should_throwAppError_when_noAuthzProvided() { public void should_throwAppError_when_noAuthzProvided() {
when(headers.getAuthorization()).thenReturn(""); when(headers.getAuthorization()).thenReturn("");
final String USER_EMAIL = "test@test.com"; final String USER_EMAIL = "test@test.com";
this.sut.hasAnyPermission(ROLE1, ROLE2); this.sut.hasAnyPermission(ROLE1, ROLE2);
assertEquals(USER_EMAIL, this.headers.getUserEmail()); assertEquals(USER_EMAIL, this.headers.getUserEmail());
} }
......
...@@ -16,6 +16,12 @@ ...@@ -16,6 +16,12 @@
package org.opengroup.osdu.notification.auth; 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.IEntitlementsFactory;
import org.opengroup.osdu.core.common.entitlements.IEntitlementsService; import org.opengroup.osdu.core.common.entitlements.IEntitlementsService;
import org.opengroup.osdu.core.common.http.HttpResponse; import org.opengroup.osdu.core.common.http.HttpResponse;
...@@ -24,14 +30,8 @@ import org.opengroup.osdu.core.common.model.entitlements.AuthorizationResponse; ...@@ -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.EntitlementsException;
import org.opengroup.osdu.core.common.model.entitlements.GroupInfo; 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.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.model.http.AppException;
import org.opengroup.osdu.core.common.entitlements.AuthorizationServiceImpl; import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -48,50 +48,50 @@ public class AuthorizationServiceEntitlementsTest { ...@@ -48,50 +48,50 @@ public class AuthorizationServiceEntitlementsTest {
@Mock @Mock
private IEntitlementsFactory entitlementsFactory; private IEntitlementsFactory entitlementsFactory;
@Mock @Mock
private IEntitlementsService service; private IEntitlementsService service;
@Mock @Mock
private JaxRsDpsLog log; private JaxRsDpsLog log;
@InjectMocks @InjectMocks
private AuthorizationServiceImpl sut; private AuthorizationServiceImpl sut;
@Before @Before
public void setup(){ public void setup() {
when(entitlementsFactory.create(any())).thenReturn(service); when(entitlementsFactory.create(any())).thenReturn(service);
} }
@Test @Test
public void should_returnUser_when_ussrHasPermission()throws EntitlementsException { public void should_returnUser_when_userHasPermission() throws EntitlementsException {
sut = createSut("service.register.user"); sut = createSut("service.register.user");
AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user"); AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user");
assertEquals("akelham@bbc.com", result.getUser()); assertEquals("akelham@bbc.com", result.getUser());
} }
@Test @Test
public void should_returnUser_when_ussrHasAnyPermission()throws EntitlementsException { public void should_returnUser_when_userHasAnyPermission() throws EntitlementsException {
sut = createSut("service.register.editor"); sut = createSut("service.register.editor");
AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user", "service.register.editor"); AuthorizationResponse result = sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.user", "service.register.editor");
assertEquals("akelham@bbc.com", result.getUser()); assertEquals("akelham@bbc.com", result.getUser());
} }
@Test @Test
public void should_throwUnauthorized_when_userDoesNotHaveRequiredPermission()throws EntitlementsException { public void should_throwUnauthorized_when_userDoesNotHaveRequiredPermission() throws EntitlementsException {
sut = createSut("service.register.user"); sut = createSut("service.register.user");
try { try {
sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor");
fail("expected exception"); fail("expected exception");
}catch(AppException ex){ } catch (AppException ex) {
assertEquals(401, ex.getError().getCode()); assertEquals(401, ex.getError().getCode());
} }
} }
@Test @Test
public void should_throwServerError_when_getGroupsThrowsServerError()throws EntitlementsException { public void should_throwServerError_when_getGroupsThrowsServerError() throws EntitlementsException {
sut = createSut("service.register.user"); sut = createSut("service.register.user");
HttpResponse response = new HttpResponse(); HttpResponse response = new HttpResponse();
response.setResponseCode(500); response.setResponseCode(500);
...@@ -99,13 +99,13 @@ public class AuthorizationServiceEntitlementsTest { ...@@ -99,13 +99,13 @@ public class AuthorizationServiceEntitlementsTest {
try { try {
sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor");
fail("expected exception"); fail("expected exception");
}catch(AppException ex){ } catch (AppException ex) {
assertEquals(500, ex.getError().getCode()); assertEquals(500, ex.getError().getCode());
} }
} }
@Test @Test
public void should_throw400AppError_when_getGroupsThrows400EntitlementsError()throws EntitlementsException { public void should_throw400AppError_when_getGroupsThrows400EntitlementsError() throws EntitlementsException {
sut = createSut("service.register.user"); sut = createSut("service.register.user");
HttpResponse response = new HttpResponse(); HttpResponse response = new HttpResponse();
response.setResponseCode(400); response.setResponseCode(400);
...@@ -113,7 +113,7 @@ public class AuthorizationServiceEntitlementsTest { ...@@ -113,7 +113,7 @@ public class AuthorizationServiceEntitlementsTest {
try { try {
sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor"); sut.authorizeAny(DpsHeaders.createFromMap(new HashMap<>()), "service.register.editor");
fail("expected exception"); fail("expected exception");
}catch(AppException ex){ } catch (AppException ex) {
assertEquals(400, ex.getError().getCode()); assertEquals(400, ex.getError().getCode());
} }
} }
...@@ -121,7 +121,7 @@ public class AuthorizationServiceEntitlementsTest { ...@@ -121,7 +121,7 @@ public class AuthorizationServiceEntitlementsTest {
private AuthorizationServiceImpl createSut(String... roles) throws EntitlementsException { private AuthorizationServiceImpl createSut(String... roles) throws EntitlementsException {
List<GroupInfo> groupInfos = new ArrayList<>(); List<GroupInfo> groupInfos = new ArrayList<>();
for(String s : roles) { for (String s : roles) {
GroupInfo group = new GroupInfo(); GroupInfo group = new GroupInfo();
group.setName(s); group.setName(s);
groupInfos.add(group); groupInfos.add(group);
...@@ -129,12 +129,9 @@ public class AuthorizationServiceEntitlementsTest { ...@@ -129,12 +129,9 @@ public class AuthorizationServiceEntitlementsTest {
Groups output = new Groups(); Groups output = new Groups();
output.setMemberEmail("akelham@bbc.com"); output.setMemberEmail("akelham@bbc.com");
output.setGroups(groupInfos); output.setGroups(groupInfos);
when(service.getGroups()).thenReturn(output); when(service.getGroups()).thenReturn(output);
return sut; return sut;
} }
} }
...@@ -36,19 +36,38 @@ import static org.mockito.Mockito.when; ...@@ -36,19 +36,38 @@ import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
public class GsaAuthTest { public class GsaAuthTest {
private static final String GOOGLE_ID_TOKEN = "testHeader.testPayload.testSignature";
private static Subscription gsa_subscription;
@Mock @Mock
private IGoogleServiceAccount gsaTokenProvider; private IGoogleServiceAccount gsaTokenProvider;
@InjectMocks @InjectMocks
private GsaAuth sut; private GsaAuth sut;
private static Subscription gsa_subscription;
private static final String GOOGLE_ID_TOKEN = "testHeader.testPayload.testSignature";
@BeforeClass @BeforeClass
public static void setup() { public static void setup() {
setGsa_subscription(); 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 @Test
public void should_return_valid_EndpointAndHeaders_gsaClient() throws Exception { public void should_return_valid_EndpointAndHeaders_gsaClient() throws Exception {
GsaSecret secret = (GsaSecret) gsa_subscription.getSecret(); GsaSecret secret = (GsaSecret) gsa_subscription.getSecret();
...@@ -71,21 +90,4 @@ public class GsaAuthTest { ...@@ -71,21 +90,4 @@ public class GsaAuthTest {
Assert.assertEquals(pushUrl, gsa_subscription.getPushEndpoint()); 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);
}
} }
...@@ -34,19 +34,35 @@ import static org.mockito.Mockito.when; ...@@ -34,19 +34,35 @@ import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
public class HmacAuthTest { public class HmacAuthTest {
private static final String SIGNED_SIGNATURE = "testEncodedInfo.testSignature";
private static Subscription hmac_subscription;
@Mock @Mock
private ISignatureService signatureService; private ISignatureService signatureService;
@InjectMocks @InjectMocks
private HmacAuth sut; private HmacAuth sut;
private static Subscription hmac_subscription;
private static final String SIGNED_SIGNATURE = "testEncodedInfo.testSignature";
@BeforeClass @BeforeClass
public static void setup() { public static void setup() {
setHmac_subscription(); 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 @Test
public void should_return_valid_EndpointAndHeaders() throws Exception { public void should_return_valid_EndpointAndHeaders() throws Exception {
HmacSecret secret = (HmacSecret) hmac_subscription.getSecret(); HmacSecret secret = (HmacSecret) hmac_subscription.getSecret();
...@@ -67,18 +83,4 @@ public class HmacAuthTest { ...@@ -67,18 +83,4 @@ public class HmacAuthTest {
sut.getPushUrl(hmac_subscription.getPushEndpoint()); sut.getPushUrl(hmac_subscription.getPushEndpoint());
fail("should throw Exception"); 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);
}
} }
// 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);
}
}
...@@ -5,30 +5,60 @@ import org.junit.Test; ...@@ -5,30 +5,60 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; 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.http.DpsHeaders;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor; import org.opengroup.osdu.notification.provider.interfaces.IPubsubRequestBodyExtractor;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest; 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; import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
public class CredentialHeadersProviderTest { public class CredentialHeadersProviderTest {
@Mock @Mock
private HttpServletRequest httpRequest; private HttpServletRequest httpRequest;
@Mock @Mock
private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor; private IPubsubRequestBodyExtractor pubsubRequestBodyExtractor;
@Mock
private IServiceAccountJwtClient serviceAccountJwtClient;
@InjectMocks @InjectMocks
private CredentialHeadersProvider headersProvider; private CredentialHeadersProvider headersProvider;
@Before
public void setup() {
MockitoAnnotations.initMocks(CredentialHeadersProviderTest.this);
}
@Test @Test
public void testGetIsOk() throws Exception { public void testGetIsOk() throws Exception {
when(httpRequest.getMethod()).thenReturn(RequestMethod.GET.toString()); when(httpRequest.getMethod()).thenReturn(RequestMethod.GET.toString());
assertNotNull(headersProvider.getObject()); 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
...@@ -19,29 +19,44 @@ package org.opengroup.osdu.notification.di; ...@@ -19,29 +19,44 @@ package org.opengroup.osdu.notification.di;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; 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.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 javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; 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; import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RequestInfoTest { public class RequestInfoExtTest {
Map<String, String> httpHeaders;
@Mock
DpsHeaders headers;
@Mock
IPubsubRequestBodyExtractor requestBodyExtractor;
@Mock @Mock
private IAppProperties config; private IAppProperties config;
@Mock @Mock
private HttpServletRequest http; private HttpServletRequest http;
@Spy
@InjectMocks
private RequestInfoExt sut; private RequestInfoExt sut;
Map<String, String> httpHeaders;
@Before @Before
public void setup() { public void setup() {
httpHeaders = new HashMap<>(); httpHeaders = new HashMap<>();
...@@ -49,18 +64,16 @@ public class RequestInfoTest { ...@@ -49,18 +64,16 @@ public class RequestInfoTest {
httpHeaders.put("correlation-id", "cor123"); httpHeaders.put("correlation-id", "cor123");
httpHeaders.put("context", "67890"); httpHeaders.put("context", "67890");
httpHeaders.put("data-partition-id", "123"); httpHeaders.put("data-partition-id", "123");
when(http.getMethod()).thenReturn("POST"); MockitoAnnotations.initMocks(RequestInfoExtTest.this);
when(http.getHeaderNames()).thenReturn(Collections.enumeration(httpHeaders.keySet()));
httpHeaders.forEach((k,v) -> when(http.getHeader(k)).thenReturn(v));
sut = new RequestInfoExt(http);
} }
@Test @Test
public void should_includeAllHeadersExcept_when_creatingHeaders() { public void assignPartitionIdIfNotInHeaderTest() {
Map<String,String> map = this.sut.getHeaders().getHeaders(); when(http.getMethod()).thenReturn("POST");
assertEquals("cor123", map.get("correlation-id")); when(headers.getPartitionId()).thenReturn(null);
assertEquals("123", map.get("data-partition-id")); when(requestBodyExtractor.extractAttributesFromRequestBody()).thenReturn(httpHeaders);
assertEquals("aaa", map.get("authorization")); this.sut.assignPartitionIdIfNotInHeader();
assertEquals(null, map.get("context")); verify(requestBodyExtractor, times(1)).extractAttributesFromRequestBody();
} }
} }
// 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
// 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
// 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());
}
}
...@@ -16,93 +16,64 @@ ...@@ -16,93 +16,64 @@
package org.opengroup.osdu.notification.service; package org.opengroup.osdu.notification.service;
import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.http.HttpClient; import org.opengroup.osdu.core.common.http.HttpClient;
import org.opengroup.osdu.core.common.http.HttpResponse; import org.opengroup.osdu.core.common.http.HttpResponse;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; 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.core.common.notification.SubscriptionException;
import org.opengroup.osdu.notification.auth.factory.AuthFactory; import org.opengroup.osdu.notification.auth.factory.AuthFactory;
import org.opengroup.osdu.notification.auth.interfaces.SecretAuth; import org.opengroup.osdu.notification.auth.interfaces.SecretAuth;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
public class NotificationHandlerTests { 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 @Mock
private SubscriptionHandler subscriptionHandler; private SubscriptionHandler subscriptionHandler;
@Mock @Mock
private AuthFactory authFactory; private AuthFactory authFactory;
@Mock @Mock
private SecretAuth secretAuth; private SecretAuth secretAuth;
@Mock @Mock
private HttpClient httpClient; private HttpClient httpClient;
@Mock @Mock
private JaxRsDpsLog log; private JaxRsDpsLog log;
@InjectMocks @InjectMocks
private NotificationHandler sut; 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 @BeforeClass
public static void setup() { public static void setup() {
setHmac_subscription(); setHmac_subscription();
setGsa_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() { private static void setGsa_subscription() {
gsa_subscription = new Subscription(); gsa_subscription = new Subscription();
gsa_subscription.setName("gsa_test_subscription"); gsa_subscription.setName("gsa_test_subscription");
...@@ -118,7 +89,6 @@ public class NotificationHandlerTests { ...@@ -118,7 +89,6 @@ public class NotificationHandlerTests {
value.setKey("keyFile"); value.setKey("keyFile");
secret.setValue(value); secret.setValue(value);
gsa_subscription.setSecret(secret); gsa_subscription.setSecret(secret);
} }
private static void setHmac_subscription() { private static void setHmac_subscription() {
...@@ -134,4 +104,38 @@ public class NotificationHandlerTests { ...@@ -134,4 +104,38 @@ public class NotificationHandlerTests {
secret.setValue("testsecret"); secret.setValue("testsecret");
hmac_subscription.setSecret(secret); 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");
}
} }
...@@ -22,41 +22,41 @@ import org.junit.Test; ...@@ -22,41 +22,41 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.http.HttpResponse; 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.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.model.notification.Subscription;
import org.opengroup.osdu.core.common.notification.ISubscriptionFactory; import org.opengroup.osdu.core.common.notification.ISubscriptionFactory;
import org.opengroup.osdu.core.common.notification.ISubscriptionService; import org.opengroup.osdu.core.common.notification.ISubscriptionService;
import org.opengroup.osdu.core.common.notification.SubscriptionException; import org.opengroup.osdu.core.common.notification.SubscriptionException;
import org.opengroup.osdu.core.common.notification.SubscriptionService; import org.opengroup.osdu.core.common.notification.SubscriptionService;
import org.opengroup.osdu.notification.di.SubscriptionCacheFactory; import org.opengroup.osdu.notification.di.SubscriptionCacheFactory;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
public class SubscriptionHandlerTests { public class SubscriptionHandlerTest {
private static final String NOTIFICATION_ID = "test-notification-id";
@Mock @Mock
private ISubscriptionFactory subscriptionFactory; private ISubscriptionFactory subscriptionFactory;
@Mock @Mock
private SubscriptionCacheFactory subscriptionCacheFactory; private SubscriptionCacheFactory subscriptionCacheFactory;
@Mock @Mock
private ObjectMapper objectMapper; private ObjectMapper objectMapper;
@InjectMocks @InjectMocks
private SubscriptionHandler sut; private SubscriptionHandler sut;
private static final String NOTIFICATION_ID = "test-notification-id";
@Test(expected = AppException.class) @Test(expected = AppException.class)
public void should_throwException_whenSubscriptionNotFound() throws Exception { public void should_throwException_whenSubscriptionNotFound() throws Exception {
when(this.subscriptionCacheFactory.get(any())).thenReturn(null); when(this.subscriptionCacheFactory.get(any())).thenReturn(null);
...@@ -64,23 +64,6 @@ public class SubscriptionHandlerTests { ...@@ -64,23 +64,6 @@ public class SubscriptionHandlerTests {
when(this.subscriptionFactory.create(any())).thenReturn(subscriptionService); when(this.subscriptionFactory.create(any())).thenReturn(subscriptionService);
HttpResponse response = new HttpResponse(); HttpResponse response = new HttpResponse();
when(subscriptionService.query(any())).thenThrow(new SubscriptionException("error", response)); 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); this.sut.getSubscriptionFromCache(NOTIFICATION_ID);
fail("should throw AppException"); fail("should throw AppException");
} }
......
...@@ -2,6 +2,8 @@ package org.opengroup.osdu.notification.swagger; ...@@ -2,6 +2,8 @@ package org.opengroup.osdu.notification.swagger;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
...@@ -9,6 +11,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder ...@@ -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.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@RunWith(MockitoJUnitRunner.class)
public class HomeControllerTest { public class HomeControllerTest {
private MockMvc mockMvc; private MockMvc mockMvc;
......
// 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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment