use of org.sagebionetworks.bridge.services.AppService in project BridgeServer2 by Sage-Bionetworks.
the class StrictValidationHandlerTest method schemaless.
@Test
public void schemaless() throws Exception {
// Set up mocks.
AppService mockAppService = mock(AppService.class);
UploadSchemaService mockUploadSchemaService = mock(UploadSchemaService.class);
handler.setAppService(mockAppService);
handler.setUploadSchemaService(mockUploadSchemaService);
// Create record with no schema.
HealthDataRecord record = HealthDataRecord.create();
record.setData(BridgeObjectMapper.get().createObjectNode());
record.setSchemaId(null);
record.setSchemaRevision(null);
context.setHealthDataRecord(record);
// Execute. No error messages.
handler.handle(context);
assertTrue(context.getMessageList().isEmpty());
// We don't ever use the dependent services.
verifyZeroInteractions(mockAppService, mockUploadSchemaService);
}
use of org.sagebionetworks.bridge.services.AppService in project BridgeServer2 by Sage-Bionetworks.
the class SmsControllerTest method before.
@BeforeMethod
public void before() {
// Mock app service.
AppService mockAppService = mock(AppService.class);
when(mockAppService.getApp(TEST_APP_ID)).thenReturn(DUMMY_APP);
// Mock SMS service.
mockParticipantService = mock(ParticipantService.class);
mockSmsService = mock(SmsService.class);
// Set up controller.
controller = spy(new SmsController());
controller.setParticipantService(mockParticipantService);
controller.setSmsService(mockSmsService);
controller.setAppService(mockAppService);
// Mock get session.
UserSession session = new UserSession();
session.setAppId(TEST_APP_ID);
doReturn(session).when(controller).getAuthenticatedSession(ADMIN);
}
use of org.sagebionetworks.bridge.services.AppService in project BridgeServer2 by Sage-Bionetworks.
the class CompoundActivityDefinitionControllerTest method setup.
@BeforeMethod
public void setup() {
// mock session
UserSession mockSession = new UserSession();
mockSession.setAppId(TEST_APP_ID);
// mock app service
appService = mock(AppService.class);
// mock def service
defService = mock(CompoundActivityDefinitionService.class);
// spy controller
controller = spy(new CompoundActivityDefinitionController());
doReturn(mockSession).when(controller).getAuthenticatedSession(any());
controller.setCompoundActivityDefService(defService);
controller.setAppService(appService);
mockRequest = mock(HttpServletRequest.class);
mockResponse = mock(HttpServletResponse.class);
doReturn(mockRequest).when(controller).request();
doReturn(mockResponse).when(controller).response();
}
use of org.sagebionetworks.bridge.services.AppService in project BridgeServer2 by Sage-Bionetworks.
the class UploadHandlersEndToEndTest method test.
private void test(UploadSchema schema, Survey survey, Map<String, String> fileMap, String nonZippedFileContent) throws Exception {
// Set up zip service.
UploadArchiveService unzipService = new UploadArchiveService();
if (upload.isZipped()) {
// fileMap is in strings. Convert to bytes so we can use the Zipper.
Map<String, byte[]> fileBytesMap = new HashMap<>();
for (Map.Entry<String, String> oneFile : fileMap.entrySet()) {
String filename = oneFile.getKey();
String fileString = oneFile.getValue();
fileBytesMap.put(filename, fileString.getBytes(Charsets.UTF_8));
}
// Add metadata.json to the fileBytesMap.
fileBytesMap.put("metadata.json", METADATA_JSON_CONTENT);
// For zipping, we use the real service.
unzipService.setMaxNumZipEntries(1000000);
unzipService.setMaxZipEntrySize(1000000);
rawFile = unzipService.zip(fileBytesMap);
} else {
// If it's not zipped, use the nonZippedFileContent as the raw file.
rawFile = nonZippedFileContent.getBytes(Charsets.UTF_8);
}
// Set up UploadFileHelper
DigestUtils mockMd5DigestUtils = mock(DigestUtils.class);
when(mockMd5DigestUtils.digest(any(File.class))).thenReturn(TestConstants.MOCK_MD5);
when(mockMd5DigestUtils.digest(any(byte[].class))).thenReturn(TestConstants.MOCK_MD5);
UploadFileHelper uploadFileHelper = new UploadFileHelper();
uploadFileHelper.setFileHelper(inMemoryFileHelper);
uploadFileHelper.setMd5DigestUtils(mockMd5DigestUtils);
uploadFileHelper.setS3Helper(mockS3UploadHelper);
// set up S3DownloadHandler - mock S3 Helper
// "S3" returns file unencrypted for simplicity of testing
S3Helper mockS3DownloadHelper = mock(S3Helper.class);
doAnswer(invocation -> {
File destFile = invocation.getArgument(2);
inMemoryFileHelper.writeBytes(destFile, rawFile);
// Required return
return null;
}).when(mockS3DownloadHelper).downloadS3File(eq(TestConstants.UPLOAD_BUCKET), eq(UPLOAD_ID), any());
S3DownloadHandler s3DownloadHandler = new S3DownloadHandler();
s3DownloadHandler.setFileHelper(inMemoryFileHelper);
s3DownloadHandler.setS3Helper(mockS3DownloadHelper);
// set up DecryptHandler - For ease of tests, this will just return the input verbatim.
UploadArchiveService mockUploadArchiveService = mock(UploadArchiveService.class);
when(mockUploadArchiveService.decrypt(eq(TEST_APP_ID), any(InputStream.class))).thenAnswer(invocation -> invocation.getArgument(1));
DecryptHandler decryptHandler = new DecryptHandler();
decryptHandler.setFileHelper(inMemoryFileHelper);
decryptHandler.setUploadArchiveService(mockUploadArchiveService);
// Set up UnzipHandler
UnzipHandler unzipHandler = new UnzipHandler();
unzipHandler.setFileHelper(inMemoryFileHelper);
unzipHandler.setUploadArchiveService(unzipService);
// Set up InitRecordHandler
InitRecordHandler initRecordHandler = new InitRecordHandler();
initRecordHandler.setFileHelper(inMemoryFileHelper);
// mock schema service
UploadSchemaService mockUploadSchemaService = mock(UploadSchemaService.class);
if (schema != null) {
when(mockUploadSchemaService.getUploadSchemaByIdAndRev(TEST_APP_ID, schema.getSchemaId(), schema.getRevision())).thenReturn(schema);
when(mockUploadSchemaService.getUploadSchemaByIdAndRevNoThrow(TEST_APP_ID, schema.getSchemaId(), schema.getRevision())).thenReturn(schema);
}
// mock survey service
SurveyService mockSurveyService = mock(SurveyService.class);
if (survey != null) {
when(mockSurveyService.getSurvey(TEST_APP_ID, new GuidCreatedOnVersionHolderImpl(survey.getGuid(), survey.getCreatedOn()), false, true)).thenReturn(survey);
}
// set up IosSchemaValidationHandler
IosSchemaValidationHandler2 iosSchemaValidationHandler = new IosSchemaValidationHandler2();
iosSchemaValidationHandler.setFileHelper(inMemoryFileHelper);
iosSchemaValidationHandler.setUploadFileHelper(uploadFileHelper);
iosSchemaValidationHandler.setUploadSchemaService(mockUploadSchemaService);
iosSchemaValidationHandler.setSurveyService(mockSurveyService);
// set up GenericUploadFormatHandler
GenericUploadFormatHandler genericUploadFormatHandler = new GenericUploadFormatHandler();
genericUploadFormatHandler.setFileHelper(inMemoryFileHelper);
genericUploadFormatHandler.setUploadFileHelper(uploadFileHelper);
genericUploadFormatHandler.setUploadSchemaService(mockUploadSchemaService);
genericUploadFormatHandler.setSurveyService(mockSurveyService);
// set up UploadFormatHandler
UploadFormatHandler uploadFormatHandler = new UploadFormatHandler();
uploadFormatHandler.setV1LegacyHandler(iosSchemaValidationHandler);
uploadFormatHandler.setV2GenericHandler(genericUploadFormatHandler);
// set up StrictValidationHandler
StrictValidationHandler strictValidationHandler = new StrictValidationHandler();
strictValidationHandler.setUploadSchemaService(mockUploadSchemaService);
AppService mockAppService = mock(AppService.class);
when(mockAppService.getApp(TEST_APP_ID)).thenReturn(APP);
strictValidationHandler.setAppService(mockAppService);
Enrollment enrollment = Enrollment.create(TEST_APP_ID, "test-study", "userId", EXTERNAL_ID);
// set up TranscribeConsentHandler
Account account = Account.create();
account.setDataGroups(ImmutableSet.of("parkinson", "test_user"));
account.setSharingScope(SharingScope.SPONSORS_AND_PARTNERS);
account.setEnrollments(ImmutableSet.of(enrollment));
AccountService mockAccountService = mock(AccountService.class);
when(mockAccountService.getAccount(any())).thenReturn(Optional.of(account));
ParticipantService mockParticipantService = mock(ParticipantService.class);
when(mockParticipantService.getStudyStartTime(any())).thenReturn(STUDY_START_TIME);
TranscribeConsentHandler transcribeConsentHandler = new TranscribeConsentHandler();
transcribeConsentHandler.setAccountService(mockAccountService);
transcribeConsentHandler.setParticipantService(mockParticipantService);
// Set up UploadRawZipHandler.
UploadRawZipHandler uploadRawZipHandler = new UploadRawZipHandler();
uploadRawZipHandler.setUploadFileHelper(uploadFileHelper);
// set up UploadArtifactsHandler
UploadArtifactsHandler uploadArtifactsHandler = new UploadArtifactsHandler();
uploadArtifactsHandler.setHealthDataService(mockHealthDataService);
// set up task factory
List<UploadValidationHandler> handlerList = ImmutableList.of(s3DownloadHandler, decryptHandler, unzipHandler, initRecordHandler, uploadFormatHandler, strictValidationHandler, transcribeConsentHandler, uploadRawZipHandler, uploadArtifactsHandler);
UploadValidationTaskFactory taskFactory = new UploadValidationTaskFactory();
taskFactory.setFileHelper(inMemoryFileHelper);
taskFactory.setHandlerList(handlerList);
taskFactory.setUploadDao(mockUploadDao);
taskFactory.setHealthDataService(mockHealthDataService);
// create task, execute
UploadValidationTask task = taskFactory.newTask(TEST_APP_ID, upload);
task.run();
}
use of org.sagebionetworks.bridge.services.AppService in project BridgeServer2 by Sage-Bionetworks.
the class StrictValidationHandlerTest method test.
private void test(List<UploadFieldDefinition> additionalFieldDefList, Map<String, byte[]> additionalAttachmentMap, JsonNode additionalJsonNode, List<String> expectedErrorList, UploadValidationStrictness uploadValidationStrictness) throws Exception {
// Basic schema with a basic attachment, basic field, and additional fields.
UploadSchema testSchema = UploadSchema.create();
List<UploadFieldDefinition> fieldDefList = new ArrayList<>();
fieldDefList.add(new UploadFieldDefinition.Builder().withName("attachment blob").withType(UploadFieldType.ATTACHMENT_BLOB).build());
fieldDefList.add(new UploadFieldDefinition.Builder().withName("string").withType(UploadFieldType.STRING).build());
if (additionalFieldDefList != null) {
fieldDefList.addAll(additionalFieldDefList);
}
testSchema.setFieldDefinitions(fieldDefList);
// mock schema service
UploadSchemaService mockSchemaService = mock(UploadSchemaService.class);
when(mockSchemaService.getUploadSchemaByIdAndRev(TEST_APP_ID, "test-schema", 1)).thenReturn(testSchema);
handler.setUploadSchemaService(mockSchemaService);
// mock app service - this is to get the shouldThrow (strictUploadValidationEnabled) flag
DynamoApp testApp = new DynamoApp();
testApp.setUploadValidationStrictness(uploadValidationStrictness);
AppService mockAppService = mock(AppService.class);
when(mockAppService.getApp(TEST_APP_ID)).thenReturn(testApp);
handler.setAppService(mockAppService);
// set up JSON data
String jsonDataString = "{\n" + " \"string\":\"This is a string\"\n" + "}";
ObjectNode jsonDataNode = (ObjectNode) BridgeObjectMapper.get().readTree(jsonDataString);
if (additionalJsonNode != null) {
ObjectNode additionalObjectNode = (ObjectNode) additionalJsonNode;
Iterator<Map.Entry<String, JsonNode>> additionalJsonIter = additionalObjectNode.fields();
while (additionalJsonIter.hasNext()) {
Map.Entry<String, JsonNode> oneAdditionalJson = additionalJsonIter.next();
jsonDataNode.set(oneAdditionalJson.getKey(), oneAdditionalJson.getValue());
}
}
// We now upload attachments before we call StrictValidationHandler. To handle this, write another entry into
// the jsonDataNode with a dummy attachment ID.
jsonDataNode.put("attachment blob", DUMMY_ATTACHMENT_ID);
if (additionalAttachmentMap != null) {
for (String oneAttachmentName : additionalAttachmentMap.keySet()) {
jsonDataNode.put(oneAttachmentName, DUMMY_ATTACHMENT_ID);
}
}
// write JSON data to health data record builder
HealthDataRecord record = HealthDataRecord.create();
record.setData(jsonDataNode);
record.setSchemaId("test-schema");
record.setSchemaRevision(1);
context.setHealthDataRecord(record);
if (expectedErrorList == null || expectedErrorList.isEmpty()) {
// In all test cases, we successfully handle and have no error messages.
handler.handle(context);
assertTrue(context.getMessageList().isEmpty());
} else {
if (uploadValidationStrictness == UploadValidationStrictness.STRICT) {
// If strict, we need to catch that exception.
try {
handler.handle(context);
fail("Expected exception");
} catch (UploadValidationException ex) {
for (String oneExpectedError : expectedErrorList) {
assertTrue(ex.getMessage().contains(oneExpectedError), "Expected error: " + oneExpectedError);
}
}
} else {
// Handle normally.
handler.handle(context);
}
// Error messages in context.
// We don't want to do string matching. Instead, the quickest way to verify this is to concatenate the
// context message list together and make sure our expected strings are in there.
String concatMessage = Joiner.on('\n').join(context.getMessageList());
for (String oneExpectedError : expectedErrorList) {
assertTrue(concatMessage.contains(oneExpectedError), "Expected error: " + oneExpectedError);
}
if (uploadValidationStrictness == UploadValidationStrictness.REPORT) {
// If strictness is REPORT, do the same for record.validationErrors.
String recordValidationErrors = record.getValidationErrors();
for (String oneExpectedError : expectedErrorList) {
assertTrue(recordValidationErrors.contains(oneExpectedError), "Expected error: " + oneExpectedError);
}
}
}
}
Aggregations