Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • osdu/platform/security-and-compliance/legal
  • alanbraz-ibm/legal
  • pfarrell/legal
  • ankitsharma/legal
  • manishk/legal
  • harshit283/legal
6 results
Show changes
Commits on Source (62)
Showing
with 571 additions and 54 deletions
package org.opengroup.osdu.legal.api;
import com.google.gson.Gson;
import java.util.Collections;
import org.opengroup.osdu.legal.countries.LegalTagCountriesService;
import org.opengroup.osdu.legal.logging.AuditLogger;
import org.opengroup.osdu.legal.tags.LegalTagService;
......@@ -137,7 +138,7 @@ public class LegalTagApi {
output.setPersonalDataTypes(allowedLegaltagPropertyValues.getPersonalDataType());
output.setSecurityClassifications(allowedLegaltagPropertyValues.getSecurityClassifications());
output.setDataTypes(allowedLegaltagPropertyValues.getDataTypes());
auditLogger.readLegalPropertiesSuccess();
auditLogger.readLegalPropertiesSuccess(Collections.singletonList(output.toString()));
return new ResponseEntity<ReadablePropertyValues>(output, HttpStatus.OK);
}
......
......@@ -82,25 +82,25 @@ public class AuditEvents {
.build();
}
public AuditPayload getReadLegalPropertiesEventSuccess() {
public AuditPayload getReadLegalPropertiesEventSuccess(List<String> resources) {
return AuditPayload.builder()
.action(AuditAction.READ)
.status(AuditStatus.SUCCESS)
.user(this.user)
.actionId(READ_ACTION_ID)
.message(READ_MESSAGE_SUCCESS)
.resources(singletonList(PROPERTY_VALUE))
.resources(resources)
.build();
}
public AuditPayload getReadLegalPropertiesEventFail() {
public AuditPayload getReadLegalPropertiesEventFail(List<String> resources) {
return AuditPayload.builder()
.action(AuditAction.READ)
.status(AuditStatus.FAILURE)
.user(this.user)
.actionId(READ_ACTION_ID)
.message(READ_MESSAGE_FAILURE)
.resources(singletonList(PROPERTY_VALUE))
.resources(resources)
.build();
}
......
......@@ -63,12 +63,12 @@ public class AuditLogger {
this.writeLog(this.getEvents().getLegalTagStatusJobEventFail(resources));
}
public void readLegalPropertiesSuccess() {
this.writeLog(this.getEvents().getReadLegalPropertiesEventSuccess());
public void readLegalPropertiesSuccess(List<String> resources) {
this.writeLog(this.getEvents().getReadLegalPropertiesEventSuccess(resources));
}
public void readLegalPropertiesFail() {
this.writeLog(this.getEvents().getReadLegalPropertiesEventFail());
public void readLegalPropertiesFail(List<String> resources) {
this.writeLog(this.getEvents().getReadLegalPropertiesEventFail(resources));
}
public void validateLegalTagSuccess() {
......
......@@ -14,20 +14,21 @@
package org.opengroup.osdu.legal.middleware;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import javassist.NotFoundException;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.inject.Inject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.google.gson.Gson;
import javassist.NotFoundException;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
......@@ -36,21 +37,14 @@ import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.opengroup.osdu.core.common.model.http.AppException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@RestController
@RestControllerAdvice
public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {
private static final Gson gson = new Gson();
......@@ -74,7 +68,7 @@ public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {
return this.getErrorResponse(
new AppException(HttpStatus.BAD_REQUEST.value(), "Bad JSON format", e.getMessage()));
}
@ExceptionHandler(UnrecognizedPropertyException.class)
protected ResponseEntity<Object> handleValidationException(UnrecognizedPropertyException e) {
return this.getErrorResponse(
......@@ -124,13 +118,24 @@ public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(@NonNull HttpRequestMethodNotSupportedException e,
@NonNull HttpHeaders headers,
@NonNull HttpStatus status,
@NonNull WebRequest request) {
return this.getErrorResponse(
@NonNull WebRequest request) {
return this.getErrorResponse(
new AppException(HttpStatus.METHOD_NOT_ALLOWED.value(), "Method not found.",
"Method not found.", e));
}
private ResponseEntity<Object> getErrorResponse(AppException e) {
@Override
@NonNull
protected ResponseEntity<Object> handleMethodArgumentNotValid(@NonNull MethodArgumentNotValidException e,
@NonNull HttpHeaders headers,
@NonNull HttpStatus status,
@NonNull WebRequest request) {
return this.getErrorResponse(
new AppException(HttpStatus.BAD_REQUEST.value(), "Validation failed.",
"Validation failed.", e));
}
public ResponseEntity<Object> getErrorResponse(AppException e) {
String exceptionMsg = e.getError().getMessage();
......@@ -140,6 +145,6 @@ public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {
this.logger.warning(exceptionMsg, e);
}
return new ResponseEntity<Object>(gson.toJson(exceptionMsg), HttpStatus.resolve(e.getError().getCode()));
return new ResponseEntity<Object>(gson.toJson(exceptionMsg),HttpStatus.resolve(e.getError().getCode()));
}
}
\ No newline at end of file
// Copyright 2017-2020, Schlumberger
//
// 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.legal.middleware;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalOtherExceptionMapper {
private GlobalExceptionMapper mapper;
public GlobalOtherExceptionMapper(GlobalExceptionMapper mapper) {
this.mapper = mapper;
}
@ExceptionHandler(Exception.class)
protected ResponseEntity<Object> handleGeneralException(Exception e) {
return mapper.getErrorResponse(
new AppException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Server error.",
"An unknown error has occurred.", e));
}
}
......@@ -268,6 +268,6 @@ public class LegalTagApiTests {
public void shouldCreateAuditLogs_when_getLegalTagProperties() {
sut.getLegalTagProperties();
verify(auditLogger).readLegalPropertiesSuccess();
verify(auditLogger).readLegalPropertiesSuccess(any());
}
}
......@@ -67,13 +67,13 @@ public class AuditLoggerTests {
@Test
public void should_writeLegalTagReadPropertiesSuccessEvent(){
sut.readLegalPropertiesSuccess();
sut.readLegalPropertiesSuccess(any());
verify(log).audit(any());
}
@Test
public void should_writeLegalTagReadPropertiesFailEvent(){
sut.readLegalPropertiesFail();
sut.readLegalPropertiesFail(any());
verify(log).audit(any());
}
......
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true
......@@ -116,6 +116,13 @@
<scope>compile</scope>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--
Override the spring-boot version of these dependencies to the ones
required by the azure-core library. This needs to be done for each
......@@ -201,6 +208,25 @@
</deployment>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
......@@ -30,9 +30,9 @@ import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Component
public class LegalTagPublisherImpl implements ILegalTagPublisher {
@Inject
private ITopicClientFactory topicClientFactory;
......
......@@ -14,18 +14,32 @@
package org.opengroup.osdu.legal.azure.security;
import lombok.NoArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@NoArgsConstructor
@Controller
public class WhoamiController {
private SecurityContext securityContext;
// Constructor made for unit testing
WhoamiController(SecurityContext securityContext) {
this.securityContext = securityContext;
}
@RequestMapping(value = "/whoami")
@ResponseBody
public String whoami() {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// Added for unit testing
if (securityContext == null)
securityContext = SecurityContextHolder.getContext();
final Authentication auth = securityContext.getAuthentication();
String userName = auth.getName();
String roles = String.valueOf(auth.getAuthorities());
......
......@@ -56,6 +56,7 @@ spring.application.name=legal-azure
#logging configuration
logging.transaction.enabled=true
logging.slf4jlogger.enabled=true
logging.mdccontext.enabled=true
#TenantFactory Configuration
tenantFactoryImpl.required=true
......
// 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.legal.azure.jobs;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.MessageBody;
import com.microsoft.azure.servicebus.TopicClient;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.azure.servicebus.ITopicClientFactory;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.opengroup.osdu.core.common.model.http.DpsHeaders;
import org.opengroup.osdu.core.common.model.legal.StatusChangedTags;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class LegalTagPublisherImplTest {
private static final String DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID = "data-partition-account-id";
private static final String CORRELATION_ID = "correlation-id";
private static final String USER_EMAIL = "user@email.com";
private static final String PARTITION_ID = "partition-id";
@Mock
private JaxRsDpsLog logger;
@Mock
private ITopicClientFactory topicClientFactory;
@Mock
private TopicClient topicClient;
@Mock
private DpsHeaders headers;
@InjectMocks
private LegalTagPublisherImpl sut;
@Before
public void init() throws ServiceBusException, InterruptedException {
doReturn(DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID).when(headers).getPartitionIdWithFallbackToAccountId();
doReturn(CORRELATION_ID).when(headers).getCorrelationId();
doReturn(USER_EMAIL).when(headers).getUserEmail();
doReturn(PARTITION_ID).when(headers).getPartitionId();
doReturn(topicClient).when(topicClientFactory).getClient(eq(PARTITION_ID), any());
}
@Test
public void testPublishLegalTag() throws Exception {
StatusChangedTags tags = new StatusChangedTags();
sut.publish("project-id", headers, tags);
ArgumentCaptor<Message> msg = ArgumentCaptor.forClass(Message.class);
ArgumentCaptor<String> log = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Exception> exception = ArgumentCaptor.forClass(Exception.class);
verify(logger).info(log.capture());
assertEquals("Storage publishes message " + CORRELATION_ID, log.getValue());
verify(topicClient).send(msg.capture());
Map<String, Object> properties = msg.getValue().getProperties();
assertEquals(DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID, properties.get(DpsHeaders.ACCOUNT_ID));
assertEquals(DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID, properties.get(DpsHeaders.DATA_PARTITION_ID));
assertEquals(CORRELATION_ID, properties.get(DpsHeaders.CORRELATION_ID));
assertEquals(USER_EMAIL, properties.get(DpsHeaders.USER_EMAIL));
MessageBody messageBody = msg.getValue().getMessageBody();
Gson gson = new Gson();
String messageKey = "message";
String dataKey = "data";
JsonObject jsonObjectMessage = gson.fromJson(new String(messageBody.getBinaryData().get(0)), JsonObject.class);
JsonObject jsonObject = (JsonObject) jsonObjectMessage.get(messageKey);
assertEquals(DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID, jsonObject.get(DpsHeaders.ACCOUNT_ID).getAsString());
assertEquals(DATA_PARTITION_WITH_FALLBACK_ACCOUNT_ID, jsonObject.get(DpsHeaders.DATA_PARTITION_ID).getAsString());
assertEquals(CORRELATION_ID, jsonObject.get(DpsHeaders.CORRELATION_ID).getAsString());
assertEquals(USER_EMAIL, jsonObject.get(DpsHeaders.USER_EMAIL).getAsString());
assertEquals(gson.toJsonTree(tags), jsonObject.get(dataKey));
}
}
// 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.legal.azure.security;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class WhoamiControllerTest {
private static final String userName = "username";
private static final String roles = "roles";
private static final String details = "details";
@InjectMocks
private WhoamiController sut;
private class DummyPrincipal {
@Override
public String toString() {
return details;
}
}
public class DummyAuthority extends ArrayList {
@Override
public String toString() {
return roles;
}
}
@Before
public void init() {
Authentication auth = mock(Authentication.class);
SecurityContext securityContext = mock(SecurityContext.class);
doReturn(auth).when(securityContext).getAuthentication();
doReturn(userName).when(auth).getName();
doReturn(new DummyAuthority()).when(auth).getAuthorities();
doReturn(new DummyPrincipal()).when(auth).getPrincipal();
sut = new WhoamiController(securityContext);
}
@Test
public void testWhoamiResponse() {
String response = sut.whoami();
assertEquals("user: " + userName + "<BR>roles: " + roles + "<BR>details: " + details + "<BR>", response);
}
}
// 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.legal.azure.tags.dataaccess;
import com.azure.cosmos.FeedOptions;
import com.azure.cosmos.SqlParameter;
import com.azure.cosmos.SqlParameterList;
import com.azure.cosmos.SqlQuerySpec;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.azure.cosmosdb.CosmosStore;
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.legal.LegalTag;
import org.opengroup.osdu.core.common.model.legal.ListLegalTagArgs;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class LegalTagRepositoryImplTest {
private static final String dataPartitionId = "data-partition-id";
@Mock
private CosmosStore cosmosStore;
@Mock
private DpsHeaders headers;
@InjectMocks
private LegalTagRepositoryImpl sut;
@Before
public void init() {
lenient().doReturn(dataPartitionId).when(headers).getPartitionId();
}
@Test(expected = AppException.class)
public void testCreateLegalTagAlreadyExisting_throwsException() {
long id = 1234;
String strId = String.valueOf(id);
LegalTag legalTag = getLegalTagWithId(id);
Optional<LegalTag> optionalLegalTag = Optional.of(legalTag);
doReturn(optionalLegalTag).when(cosmosStore).findItem(eq(dataPartitionId), any(), any(), eq(strId), eq(strId), any());
try {
sut.create(legalTag);
} catch (AppException e) {
int errorCode = 409;
String errorMessage = "LegalTag already exists";
validateAppException(e, errorCode, errorMessage);
throw (e);
}
}
@Test
public void testCreateLegalTag_upsertItem_executesCorrectQuery() {
long id = 1234;
String strId = String.valueOf(id);
LegalTag legalTag = getLegalTagWithId(id);
long obtainedId = sut.create(legalTag);
ArgumentCaptor<LegalTagDoc> arg = ArgumentCaptor.forClass(LegalTagDoc.class);
verify(cosmosStore).upsertItem(eq(dataPartitionId), any(), any(), arg.capture());
assertEquals(arg.getValue().getId(), strId);
assertEquals(obtainedId, id);
}
@Test
public void testGetLegalTagCollections_whenIdsIsNull() {
long[] ids = null;
List<LegalTag> output = (List<LegalTag>) sut.get(ids);
assertEquals(output.size(), 0);
}
@Test
public void testGetLegalTagCollections_whenIdsIsNotNull() {
long[] ids = {1234, 9876};
String[] strIds = Arrays.stream(ids).mapToObj(String::valueOf).toArray(String[]::new);
Optional[] legalTagDocs = new Optional[2];
legalTagDocs[0] = Optional.of(new LegalTagDoc(strIds[0], getLegalTagWithId(ids[0])));
legalTagDocs[1] = Optional.of(new LegalTagDoc(strIds[0], getLegalTagWithId(ids[1])));
doReturn(legalTagDocs[0]).when(cosmosStore).findItem(eq(dataPartitionId), any(), any(), eq(strIds[0]), eq(strIds[0]), any());
doReturn(legalTagDocs[1]).when(cosmosStore).findItem(eq(dataPartitionId), any(), any(), eq(strIds[1]), eq(strIds[1]), any());
List<LegalTag> output = (List<LegalTag>) sut.get(ids);
assertEquals(output.size(), 2);
assertEquals(output.get(0).getId().longValue(), ids[0]);
assertEquals(output.get(1).getId().longValue(), ids[1]);
}
@Test
public void testDeleteLegalTag_whenLegalTagDoesNotExist() {
long id = 1234;
LegalTag legalTag = getLegalTagWithId(id);
boolean status = sut.delete(legalTag);
assertEquals(status, false);
}
@Test
public void testDeleteLegalTag_whenLegalTagExists() {
long id = 1234;
String strId = String.valueOf(id);
LegalTag legalTag = getLegalTagWithId(id);
Optional<LegalTag> optionalLegalTag = Optional.of(legalTag);
doReturn(optionalLegalTag).when(cosmosStore).findItem(eq(dataPartitionId), any(), any(), eq(strId), eq(strId), any());
boolean status = sut.delete(legalTag);
ArgumentCaptor<String> arg1 = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> arg2 = ArgumentCaptor.forClass(String.class);
verify(cosmosStore).deleteItem(eq(dataPartitionId), any(), any(), arg1.capture(), arg2.capture());
assertEquals(status, true);
assertEquals(arg1.getValue(), strId);
assertEquals(arg2.getValue(), strId);
}
@Test
public void testUpdateLegalTag_whenProvidedLegalTagIsNull() {
LegalTag legalTag = sut.update(null);
assertNull(legalTag);
}
@Test(expected = AppException.class)
public void testUpdateLegalTag_whenValidItemDoesNotExist_throwsException() {
long id = 1234;
LegalTag legalTag = getLegalTagWithId(id);
try {
sut.update(legalTag);
} catch (AppException e) {
int errorCode = 404;
String errorMessage = "Cannot update a LegalTag that does not exist";
validateAppException(e, errorCode, errorMessage);
throw (e);
}
}
@Test
public void testUpdateLegalTag_whenValidItemExists() {
long id = 1234;
String strId = String.valueOf(id);
LegalTag legalTag = getLegalTagWithId(id);
Optional<LegalTag> optionalLegalTag = Optional.of(legalTag);
doReturn(optionalLegalTag).when(cosmosStore).findItem(eq(dataPartitionId), any(), any(), eq(strId), eq(strId), any());
LegalTag obtainedLegalTag = sut.update(legalTag);
ArgumentCaptor<LegalTagDoc> arg = ArgumentCaptor.forClass(LegalTagDoc.class);
verify(cosmosStore).upsertItem(eq(dataPartitionId), any(), any(), arg.capture());
assertEquals(arg.getValue().getId(), strId);
assertEquals(obtainedLegalTag.getId().longValue(), id);
}
@Test
public void testListLegalTags_queryItems_executesCorrectQuery() {
long[] ids = {1234, 9876};
String[] strIds = Arrays.stream(ids).mapToObj(String::valueOf).toArray(String[]::new);
List<LegalTagDoc> legalTagDocs = Arrays.asList(new LegalTagDoc(strIds[0], getLegalTagWithId(ids[0])), new LegalTagDoc(strIds[1], getLegalTagWithId(ids[1])));
ArgumentCaptor<SqlQuerySpec> query = ArgumentCaptor.forClass(SqlQuerySpec.class);
ArgumentCaptor<FeedOptions> feedOptions = ArgumentCaptor.forClass(FeedOptions.class);
doReturn(legalTagDocs).when(cosmosStore).queryItems(eq(dataPartitionId), any(), any(), any(), any(), any());
ListLegalTagArgs legalTagArgs = new ListLegalTagArgs();
legalTagArgs.setIsValid(true);
List<LegalTag> output = (List<LegalTag>) sut.list(legalTagArgs);
assertEquals(output.size(), 2);
assertEquals(output.get(0).getId().longValue(), ids[0]);
assertEquals(output.get(1).getId().longValue(), ids[1]);
verify(cosmosStore).queryItems(eq(dataPartitionId), any(), any(), query.capture(), feedOptions.capture(), any());
assertEquals(query.getValue().getQueryText(), "SELECT * FROM c WHERE c.legalTag.isValid = @isValid");
assertTrue(feedOptions.getValue().getEnableCrossPartitionQuery());
SqlParameterList parameters = query.getValue().getParameters();
SqlParameter isValid = parameters.get(0);
assertEquals(isValid.getName(), "@isValid");
assertEquals(isValid.getValue(Boolean.class), true);
}
private LegalTag getLegalTagWithId(long id) {
LegalTag legalTag = new LegalTag();
legalTag.setId(id);
return legalTag;
}
private void validateAppException(AppException e, int errorCode, String errorMessage) {
assertEquals(errorCode, e.getError().getCode());
assertThat(e.getError().getMessage(), containsString(errorMessage));
}
}
......@@ -125,6 +125,7 @@ You will need to have the following environment variables defined.
| `INTEGRATION_TESTER` | `********` | Service account for API calls. Note: this user must have entitlements configured already | yes | https://console.cloud.google.com/iam-admin/serviceaccounts |
| `HOST_URL` | `http://localhsot:8080/api/legal/v1/` | - | yes | - |
| `MY_TENANT` | `osdu` | OSDU tenant used for testing | yes | - |
| `SKIP_HTTP_TESTS` | ex `true` | jetty server returns 403 when running locally when deployed jettyserver is not used and the app returns a 302 so just run against deployed version only when checking http -> https redirects. Use 'true' for Google Cloud Run | yes | - |
**Entitlements configuration for integration accounts**
......
......@@ -233,7 +233,26 @@
<configuration>
<version>1</version>
</configuration>
</plugin>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
......@@ -45,6 +45,12 @@
<artifactId>pact-jvm-provider-junit_2.12</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<repositories>
......
......@@ -5,13 +5,14 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.opengroup.osdu.legal.util.Constants.DATA_PARTITION_ID;
import com.sun.jersey.api.client.ClientResponse;
import java.util.HashMap;
import java.util.Map;
import com.sun.jersey.api.client.ClientResponse;
import java.util.Objects;
import lombok.extern.java.Log;
import org.junit.Test;
@Log
public abstract class AcceptanceBaseTest {
protected LegalTagUtils legalTagUtils;
......@@ -84,17 +85,25 @@ public abstract class AcceptanceBaseTest {
return response;
}
protected ClientResponse validateAccess(int expectedResponse) throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(DATA_PARTITION_ID, LegalTagUtils.getMyDataPartition());
ClientResponse response = legalTagUtils.send(this.getApi(), this.getHttpMethod(), legalTagUtils.accessToken(), getBody(), getQuery(), headers);
assertEquals(expectedResponse, response.getStatus());
if(expectedResponse == 204)
assertNull(response.getType());
else if(response.getType() != null) {
assertTrue(response.getType().toString().toLowerCase().indexOf("application/json") >= 0);
}
return response;
}
protected ClientResponse validateAccess(int expectedResponse) throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(DATA_PARTITION_ID, LegalTagUtils.getMyDataPartition());
ClientResponse response = legalTagUtils
.send(this.getApi(), this.getHttpMethod(), legalTagUtils.accessToken(), getBody(),
getQuery(), headers);
log.info("Response status = " + response.getStatus());
assertEquals(expectedResponse, response.getStatus());
if (expectedResponse == 204) {
if (Objects.nonNull(response.getType())) {
log.info("Content-Type = " + response.getType().toString());
assertTrue(response.getType().toString().toLowerCase().indexOf("text/html") >= 0); //Google Cloud Run specific
} else {
assertNull(response.getType());
}
} else if (response.getType() != null) {
assertTrue(response.getType().toString().toLowerCase().indexOf("application/json") >= 0);
}
return response;
}
}
\ No newline at end of file