diff --git a/pom.xml b/pom.xml index 3a01e93a..085c3228 100644 --- a/pom.xml +++ b/pom.xml @@ -169,7 +169,12 @@ io.javalin javalin - 3.13.10 + 6.7.0 + + + org.jetbrains.kotlin + kotlin-stdlib + 1.9.25 @@ -224,7 +229,7 @@ org.mockito mockito-core 5.8.0 - compile + test org.junit.jupiter @@ -253,7 +258,13 @@ net.bytebuddy byte-buddy - 1.10.4 + 1.14.10 + + + net.bytebuddy + byte-buddy-agent + 1.14.10 + test org.slf4j diff --git a/src/main/Config/AppConfig.java b/src/main/Config/AppConfig.java index 0d0e5882..26875fe9 100644 --- a/src/main/Config/AppConfig.java +++ b/src/main/Config/AppConfig.java @@ -44,6 +44,10 @@ import java.util.Optional; import lombok.SneakyThrows; import org.bson.types.ObjectId; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.session.DefaultSessionIdManager; +import org.eclipse.jetty.server.session.SessionHandler; +import org.eclipse.jetty.servlet.ServletContextHandler; public class AppConfig { public static Long ASYNC_TIME_OUT = 10L; @@ -220,7 +224,7 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/organizations", productionController.createOrg); app.before( - "/organizations/:orgId", + "/organizations/{orgId}", ctx -> { ObjectId objectId = new ObjectId(ctx.pathParam("orgId")); Optional organizationOptional = orgDao.get(objectId); @@ -232,10 +236,10 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { new HashMap<>()); } }); - app.get("/organizations/:orgId", productionController.readOrg); - app.patch("/organizations/:orgId", productionController.updateOrg); - app.delete("/organizations/:orgId", productionController.deleteOrg); - app.get("/organizations/:orgId/users", productionController.getUsersFromOrg); + app.get("/organizations/{orgId}", productionController.readOrg); + app.patch("/organizations/{orgId}", productionController.updateOrg); + app.delete("/organizations/{orgId}", productionController.deleteOrg); + app.get("/organizations/{orgId}/users", productionController.getUsersFromOrg); app.before( "/users*", @@ -258,7 +262,7 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/users", productionController.createUser); app.before( - "/users/:username", + "/users/{username}", ctx -> { String username = ctx.pathParam("username"); Optional userOptional = userDao.get(username); @@ -269,15 +273,15 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { } }); - app.get("/users/:username", productionController.readUser); - app.patch("/users/:username", productionController.updateUser); - app.delete("/users/:username", productionController.deleteUser); + app.get("/users/{username}", productionController.readUser); + app.patch("/users/{username}", productionController.updateUser); + app.delete("/users/{username}", productionController.deleteUser); /* --------------- SEARCH FUNCTIONALITY ------------- */ app.patch("/change-optional-info/", optionalUserInformationController.updateInformation); - app.get("/get-optional-info/:username", optionalUserInformationController.getInformation); + app.get("/get-optional-info/{username}", optionalUserInformationController.getInformation); app.delete( - "/delete-optional-info/:username", optionalUserInformationController.deleteInformation); + "/delete-optional-info/{username}", optionalUserInformationController.deleteInformation); app.post("/save-optional-info/", optionalUserInformationController.saveInformation); /* -------------- Billing ----------------- */ @@ -318,42 +322,38 @@ public static Javalin createJavalinApp(DeploymentLevel deploymentLevel) { } return Javalin.create( config -> { - config.asyncRequestTimeout = + config.http.asyncTimeout= ASYNC_TIME_OUT; // timeout for async requests (default is 0, no timeout) - config.autogenerateEtags = false; // auto generate etags (default is false) - config.contextPath = "/"; // context path for the http servlet (default is "/") - config.defaultContentType = - "text/plain"; // content type to use if no content type is set (default is - // "text/plain") - - config.enableCorsForOrigin( - "https://keep.id", - "https://server.keep.id", - "http://localhost", - "http://localhost:3000", - "127.0.0.1:3000"); - - config.enableDevLogging(); // enable extensive development logging for - // http and - // websocket - config.enforceSsl = false; - // log a warning if user doesn't start javalin instance (default is true) - config.logIfServerNotStarted = true; + config.http.generateEtags = false; // auto generate etags (default is false) + config.http.defaultContentType = "text/plain"; + config.router.contextPath = "/"; + config.bundledPlugins.enableCors(cors -> { + cors.addRule(rule -> { + rule.allowHost( + "https://keep.id", + "https://server.keep.id", + "http://localhost", + "http://localhost:3000", + "http://127.0.0.1:3000", + "http://localhost:3001", + "https://staged.keep.id", + "https://staging.keep.id", + "http://staging.keep.id" + ); + rule.allowCredentials = true; + rule.allowHeaders("Content-Type", "Authorization", "X-Requested-With"); + rule.allowMethods("GET", "POST", "PUT", "PATCH", "DELETE"); + }); + }); + config.showJavalinBanner = false; - config.prefer405over404 = - false; // send a 405 if handlers exist for different verb on the same path - // (default is false) - config.sessionHandler( - () -> { - try { - return SessionConfig.getSessionHandlerInstance(deploymentLevel); - } catch (Exception e) { - System.err.println("Unable to instantiate session handler."); - e.printStackTrace(); - System.exit(1); - return null; - } - }); + config.jetty.modifyServletContextHandler(ctx -> { + try { + ctx.setSessionHandler(SessionConfig.getSessionHandlerInstance(deploymentLevel)); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); }) .start(port); } diff --git a/src/main/Config/SessionConfig.java b/src/main/Config/SessionConfig.java index fffe40a2..78b3d1bb 100644 --- a/src/main/Config/SessionConfig.java +++ b/src/main/Config/SessionConfig.java @@ -44,6 +44,10 @@ public static SessionHandler getSessionHandlerInstance(DeploymentLevel deploymen return sessionHandler; } + public static void resetSessionHandler() { + sessionHandler = null; + } + private static MongoSessionDataStoreFactory mongoDataStoreFactory( String dbName, String collectionName) { MongoSessionDataStoreFactory mongoSessionDataStoreFactory = new MongoSessionDataStoreFactory(); diff --git a/src/main/File/FileController.java b/src/main/File/FileController.java index ad7bd1e0..f1b3df20 100644 --- a/src/main/File/FileController.java +++ b/src/main/File/FileController.java @@ -122,28 +122,29 @@ public FileController( UploadedFile signature = null; Date uploadDate = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()); - InputStream filestreamToUpload = file.getContent(); - String filenameToUpload = file.getFilename(); + InputStream filestreamToUpload = file.content(); + String filenameToUpload = file.filename(); switch (fileType) { case APPLICATION_PDF: case IDENTIFICATION_PDF: case FORM: log.info("Got PDF file to upload!"); - if (file.getContentType().startsWith("image")) { + if (Objects.requireNonNull(file.contentType()).startsWith("image")) { ImageToPDFService imageToPDFService = new ImageToPDFService(filestreamToUpload); Message imageToPdfServiceResponse = imageToPDFService.executeAndGetResponse(); if (imageToPdfServiceResponse == PdfMessage.INVALID_PDF) { ctx.result(imageToPdfServiceResponse.toResponseString()); + return; } filestreamToUpload = imageToPDFService.getFileStream(); filenameToUpload = - file.getFilename().substring(0, file.getFilename().lastIndexOf(".")) + file.filename().substring(0, file.filename().lastIndexOf(".")) + ".pdf"; } - filestreamToUpload.reset(); - // PDDocument pdfDocument = Loader.loadPDF(filestreamToUpload); - // title = getPDFTitle(file.getFilename(), pdfDocument); - // pdfDocument.close(); + + if (!Objects.requireNonNull(file.contentType()).startsWith("image")) { + filestreamToUpload = file.content(); + } if (toSign) { signature = Objects.requireNonNull(ctx.uploadedFile("signature")); @@ -162,7 +163,7 @@ public FileController( filenameToUpload, organizationName, annotated, - file.getContentType()); + file.contentType()); UploadFileService uploadService = new UploadFileService( fileDao, @@ -172,7 +173,7 @@ public FileController( toSign, signature == null ? Optional.empty() - : Optional.of(signature.getContent()), + : Optional.of(signature.content()), Optional.ofNullable(encryptionController)); response = uploadService.executeAndGetResponse(); break; @@ -188,7 +189,7 @@ public FileController( filenameToUpload, organizationName, annotated, - file.getContentType()); + file.contentType()); uploadService = new UploadFileService( fileDao, @@ -212,7 +213,7 @@ public FileController( filenameToUpload, organizationName, annotated, - file.getContentType()); + file.contentType()); uploadService = new UploadFileService( fileDao, diff --git a/src/main/PDF/PdfController.java b/src/main/PDF/PdfController.java index 86f5f85b..9ba6f62d 100644 --- a/src/main/PDF/PdfController.java +++ b/src/main/PDF/PdfController.java @@ -295,9 +295,9 @@ public User userCheck(String req) { organizationName, privilegeLevel, pdfType, - file.getFilename(), - file.getContentType(), - file.getContent(), + file.filename(), + file.contentType(), + file.content(), encryptionController, idCategory); response = uploadService.executeAndGetResponse(); @@ -329,9 +329,9 @@ public User userCheck(String req) { organizationName, UserType.Developer, fileIDStr, - file.getFilename(), - file.getContentType(), - file.getContent(), + Objects.requireNonNull(file).filename(), + file.contentType(), + file.content(), encryptionController); ctx.result(uploadService.executeAndGetResponse().toResponseString()); }; @@ -364,10 +364,10 @@ public User userCheck(String req) { organizationName, privilegeLevel, pdfType, - file.getFilename(), - file.getContentType(), - file.getContent(), - signature.getContent(), + file.filename(), + file.contentType(), + file.content(), + signature.content(), encryptionController); ctx.result(uploadService.executeAndGetResponse().toResponseString()); }; diff --git a/src/main/PDF/PdfControllerV2.java b/src/main/PDF/PdfControllerV2.java index d6bf4028..d50dfed7 100644 --- a/src/main/PDF/PdfControllerV2.java +++ b/src/main/PDF/PdfControllerV2.java @@ -415,7 +415,7 @@ public Message setFileParamsUploadSignedPDF(Context ctx) { UploadedFile signature = Objects.requireNonNull(ctx.uploadedFile("signature")); this.fileId = Objects.requireNonNull(ctx.formParam("applicationId")); this.formAnswers = new JSONObject(Objects.requireNonNull(ctx.formParam("formAnswers"))); - this.signatureStream = signature.getContent(); + this.signatureStream = signature.content(); } catch (Exception e) { return PdfMessage.INVALID_PARAMETER; } @@ -460,9 +460,9 @@ public Message setFileParamsUploadPDF(Context ctx) { log.info("Client uploaded document missing category"); return PdfMessage.INVALID_ID_CATEGORY; } - this.fileName = file.getFilename(); - this.fileContentType = file.getContentType(); - this.fileStream = file.getContent(); + this.fileName = file.filename(); + this.fileContentType = file.contentType(); + this.fileStream = file.content(); return null; } @@ -473,9 +473,9 @@ public Message setFileParamsUploadAnnotatedPDF(Context ctx) { return PdfMessage.INVALID_PDF; } // this.fileOrgName = ctx.formParam("fileOrgName"); - this.fileName = file.getFilename(); - this.fileContentType = file.getContentType(); - this.fileStream = file.getContent(); + this.fileName = file.filename(); + this.fileContentType = file.contentType(); + this.fileStream = file.content(); return null; } diff --git a/src/main/PDF/Services/V2Services/FillPDFServiceV2.java b/src/main/PDF/Services/V2Services/FillPDFServiceV2.java index 19bf6ee9..33710914 100644 --- a/src/main/PDF/Services/V2Services/FillPDFServiceV2.java +++ b/src/main/PDF/Services/V2Services/FillPDFServiceV2.java @@ -95,9 +95,9 @@ public Message checkFillConditions() { if (!ValidationUtils.isValidObjectId(fileId) || formAnswers == null) { return PdfMessage.INVALID_PARAMETER; } - // if (signatureStream == null) { - // return PdfMessage.SERVER_ERROR; - // } +// if (signatureStream == null) { +// return PdfMessage.SERVER_ERROR; +// } if (privilegeLevel == null) { return PdfMessage.INVALID_PRIVILEGE_TYPE; } diff --git a/src/main/User/Services/UploadPfpService.java b/src/main/User/Services/UploadPfpService.java index 1996e39a..4e27d898 100644 --- a/src/main/User/Services/UploadPfpService.java +++ b/src/main/User/Services/UploadPfpService.java @@ -33,7 +33,7 @@ public UploadPfpService(MongoDatabase db, String username, UploadedFile pfp, Str @Override public Message executeAndGetResponse() { - InputStream content = pfp.getContent(); + InputStream content = pfp.content(); Bson filter = Filters.eq("metadata.owner", username); GridFSBucket gridBucket = GridFSBuckets.create(db, "pfp"); GridFSFile grid_out = gridBucket.find(filter).first(); diff --git a/src/main/User/UserController.java b/src/main/User/UserController.java index 1e0c6c49..dabeb68f 100644 --- a/src/main/User/UserController.java +++ b/src/main/User/UserController.java @@ -27,6 +27,8 @@ import java.time.ZoneId; import java.util.*; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.Part; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject; @@ -130,7 +132,7 @@ public UserController( public Handler loginUser = ctx -> { - ctx.req.getSession().invalidate(); + Optional.ofNullable(ctx.req().getSession(false)).ifPresent(HttpSession::invalidate); JSONObject req = new JSONObject(ctx.body()); String username = req.getString("username"); String password = req.getString("password"); @@ -173,7 +175,7 @@ public UserController( */ public Handler googleLoginRequestHandler = ctx -> { - ctx.req.getSession().invalidate(); + Optional.ofNullable(ctx.req().getSession(false)).ifPresent(HttpSession::invalidate); JSONObject req = new JSONObject(ctx.body()); String redirectUri = req.optString("redirectUri", null); String originUri = req.optString("originUri", null); @@ -440,7 +442,7 @@ public UserController( public Handler logout = ctx -> { - ctx.req.getSession().invalidate(); + Optional.ofNullable(ctx.req().getSession(false)).ifPresent(HttpSession::invalidate); log.info("Signed out"); ctx.result(UserMessage.SUCCESS.toJSON().toString()); }; @@ -559,17 +561,21 @@ public static JSONObject mergeJSON( User user = optionalUser.get(); Date uploadDate = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()); + if (file == null) { + ctx.result(UserMessage.INVALID_PARAMETER.toJSON().toString()); + return; + } File fileToUpload = new File( username, uploadDate, - file.getContent(), + Objects.requireNonNull(file).content(), FileType.PROFILE_PICTURE, IdCategoryType.NONE, - file.getFilename(), + file.filename(), user.getOrganization(), false, - file.getContentType()); + file.contentType()); UploadFileService service = new UploadFileService( fileDao, diff --git a/src/test/BillingTest/DonationCheckoutServiceIntegrationTest.java b/src/test/BillingTest/DonationCheckoutServiceIntegrationTest.java deleted file mode 100644 index 647f7269..00000000 --- a/src/test/BillingTest/DonationCheckoutServiceIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package BillingTest; - -import TestUtils.TestUtils; -import kong.unirest.HttpResponse; -import kong.unirest.Unirest; -import org.json.JSONObject; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class DonationCheckoutServiceIntegrationTest { - - @BeforeClass - public static void setUp() { - TestUtils.startServer(); - } - - @Test - public void success() { // test is currently broken, we will debug once this is more important - JSONObject request = new JSONObject(); - request.put("payment_method_nonce", "fake-valid-nonce"); - request.put("amount", "10"); - HttpResponse response = - Unirest.post(TestUtils.getServerUrl() + "/donation-checkout") - .body(request.toString()) - .asString(); - assertEquals("Internal server error", response.getBody()); - } - - /** - * Unable to correctly mock failed response @Test public void failure() { - * Mockito.when(gateway.transaction().sale(transactionRequest)).thenReturn(transactionResult); - * JSONObject request = new JSONObject(); request.put("payment_method_nonce", - * "fake-processor-declined-visa-nonce"); request.put("amount", "10"); HttpResponse - * response = Unirest.post(TestUtils.getServerUrl() + "/donation-checkout") - * .body(request.toString()) .asString(); JSONObject responseJSON = - * TestUtils.responseStringToJSON(response.getBody()); - * assertThat(responseJSON.getString("status")).isEqualTo("FAILURE"); } - */ -} diff --git a/src/test/DatabaseTest/Activity/ActivityDaoImplUnitTests.java b/src/test/DatabaseTest/Activity/ActivityDaoImplUnitTests.java index 68f7619d..c2366fe7 100644 --- a/src/test/DatabaseTest/Activity/ActivityDaoImplUnitTests.java +++ b/src/test/DatabaseTest/Activity/ActivityDaoImplUnitTests.java @@ -161,6 +161,7 @@ public void update() { @Test public void delete() { + assertEquals(0, activityDao.size()); Activity activity = EntityFactory.createActivity() .withUsername("my username") @@ -169,10 +170,10 @@ public void delete() { .buildAndPersist(activityDao); Activity readActivity = activityDao.get(activity.getId()).orElseThrow(); assertTrue(areActivitiesEqual(activity, readActivity)); - + assertEquals(1, activityDao.size()); activityDao.delete(activity); assertFalse(activityDao.get(activity.getId()).isPresent()); - assertEquals(1, activityDao.size()); + assertEquals(0, activityDao.size()); } @Test diff --git a/src/test/DatabaseTest/File/FileDaoImplUnitTests.java b/src/test/DatabaseTest/File/FileDaoImplUnitTests.java index d4498877..a37ef434 100644 --- a/src/test/DatabaseTest/File/FileDaoImplUnitTests.java +++ b/src/test/DatabaseTest/File/FileDaoImplUnitTests.java @@ -28,7 +28,9 @@ public void initialize() { @After public void reset() { - fileDao.clear(); + if (fileDao != null) { + fileDao.clear(); + } } @Test diff --git a/src/test/PDFTest/AnnotationPDFServiceTest.java b/src/test/PDFTest/AnnotationPDFServiceTest.java deleted file mode 100644 index c736b69a..00000000 --- a/src/test/PDFTest/AnnotationPDFServiceTest.java +++ /dev/null @@ -1,474 +0,0 @@ -package PDFTest; - -import static PDFTest.PDFTestUtils.*; -import static TestUtils.EntityFactory.createUser; -import static TestUtils.TestUtils.getFieldValues; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.Assert.assertEquals; - -import Config.DeploymentLevel; -import Database.User.UserDao; -import Database.User.UserDaoFactory; -import PDF.PDFType; -import PDF.PdfController; -import TestUtils.TestUtils; -import User.User; -import User.UserType; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.GeneralSecurityException; -import java.util.Collections; -import kong.unirest.HttpResponse; -import kong.unirest.Unirest; -import org.apache.commons.io.FileUtils; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.*; - -public class AnnotationPDFServiceTest { - private UserDao userDao; - - @BeforeClass - public static void setUp() { - TestUtils.startServer(); - } - - @Before - public void initialize() { - userDao = UserDaoFactory.create(DeploymentLevel.TEST); - } - - @After - public void reset() { - if(this.userDao != null) { - this.userDao.clear(); - } - TestUtils.tearDownTestDB(); - TestUtils.logout(); - } - - @AfterClass - public static void tearDown() { - TestUtils.tearDownTestDB(); - } - - // ------------------ GET QUESTIONS TESTS ------------------------ // - @Test - public void getApplicationQuestionsBirthCertificateTest() - throws IOException, GeneralSecurityException { - String username = "username"; - String password = "password"; - User user = - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - // when running entire file, other documents interfere with retrieving the form. - // clearAllDocuments(); - - File applicationPDF = - new File( - resourcesFolderPath - + File.separator - + "AnnotatedPDFs" - + File.separator - + "Application_for_a_Birth_Certificate_Annotated.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - JSONArray fields = applicationsQuestionsResponseJSON.getJSONArray("fields"); - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - // Todo: We Need To Read the Correct Annotation from a CSV File - JSONArray correctFields = PDFTestUtils.csvToJSON("Test_Pennsylvania_Birth_Certificate.csv"); - // this equality is broken right now - // PDFTestUtils.checkFieldsEquality(correctFields, fields); - TestUtils.logout(); - } - - @Test - public void getApplicationQuestionsSocialSecurityCardTest() - throws IOException, GeneralSecurityException { - String username = "username"; - String password = "password"; - User user = - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File applicationPDF = new File(resourcesFolderPath + File.separator + "SSAPP_DELETE.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("ANNOTATION_ERROR"); - assertThat(applicationsQuestionsResponseJSON.getString("message")) - .isEqualTo("Field Directive not Understood for Field '1:First Name:firstName'"); - // delete(fileId, "BLANK_FORM"); - TestUtils.logout(); - } - - @Test - public void getApplicationQuestionBlankPDFTest() throws IOException, GeneralSecurityException { - String username = "username"; - String password = "password"; - User user = - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File applicationDocx = - new File(resourcesFolderPath + File.separator + "CIS_401_Final_Progress_Report.pdf"); - String fileId = uploadFileAndGetFileId(applicationDocx, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("INVALID_PDF"); - // assertThat(applicationsQuestionsResponseJSON.getJSONArray("fields").toString()) - // .isEqualTo(new JSONArray().toString()); - // delete(fileId, "BLANK_FORM"); - TestUtils.logout(); - } - - @Test - public void getApplicationQuestionMetadataTest() throws IOException, GeneralSecurityException { - // Test to get application with metadata - User user = - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File applicationPDF = - new File(resourcesFolderPath + File.separator + "Application_for_a_Birth_Certificate.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("SUCCESS"); - assertEquals("Untitled", applicationsQuestionsResponseJSON.get("title")); - } - - @Test - public void getApplicationQuestionsCaseWorkerTest() throws IOException, GeneralSecurityException { - String caseWorkerUsername = "username1"; - String caseWorkerPassword = "password1"; - String clientUsername = "username2"; - String clientPassword = "password2"; - String organization = "org1"; - // Case worker - createUser() - .withUserType(UserType.Admin) - .withUsername(caseWorkerUsername) - .withPasswordToHash(caseWorkerPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - TestUtils.login(caseWorkerUsername, caseWorkerPassword); - // Client - createUser() - .withUserType(UserType.Client) - .withUsername(clientUsername) - .withPasswordToHash(clientPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - - File applicationPDF = - new File(resourcesFolderPath + File.separator + "Application_for_a_Birth_Certificate.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", clientUsername); - HttpResponse response = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject responseJSON = TestUtils.responseStringToJSON(response.getBody()); - assertThat(responseJSON.getString("status")).isEqualTo("SUCCESS"); - assertEquals("Untitled", responseJSON.get("title")); - } - - // ------------------ FILL COMPLETED_APPLICATION TESTS ------------------------ // - - @Test - public void fillApplicationQuestionsBirthCertificateTest() - throws IOException, GeneralSecurityException { - String username = "username2"; - String password = "password"; - User user = - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File applicationPDF = new File(resourcesFolderPath + File.separator + "ss-5.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - JSONObject formAnswers = getFormAnswersTestPDFForm(applicationsQuestionsResponseJSON); - // fill out form - body = new JSONObject(); - body.put("applicationId", fileId); - body.put("formAnswers", formAnswers); - body.put("clientUsername", ""); - HttpResponse filledForm = - Unirest.post(TestUtils.getServerUrl() + "/fill-application") - .body(body.toString()) - .asFile(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - assertThat(filledForm.getStatus()).isEqualTo(200); - - // check if all fields are filled - JSONObject fieldValues = null; - try { - File filled_out_pdf = new File(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - PDDocument pdf = Loader.loadPDF(filled_out_pdf); - fieldValues = getFieldValues(new FileInputStream(filled_out_pdf)); - } catch (IOException e) { - assertThat(false).isTrue(); - } - assertThat(fieldValues).isNotNull(); - // checkFormAnswersSS5Form(fieldValues); - // delete(fileId, "BLANK_FORM"); - TestUtils.logout(); - } - - @Test - public void fillApplicationQuestionsSS5Test() throws IOException, GeneralSecurityException { - createUser() - .withUserType(UserType.Admin) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - // clearAllDocumentsForUser(username, password); - - File applicationPDF = new File(resourcesFolderPath + File.separator + "ss-5.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", ""); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - JSONObject formAnswers = getFormAnswersTestPDFForm(applicationsQuestionsResponseJSON); - // fill out form - body = new JSONObject(); - body.put("applicationId", fileId); - body.put("formAnswers", formAnswers); - body.put("clientUsername", ""); - HttpResponse filledForm = - Unirest.post(TestUtils.getServerUrl() + "/fill-application") - .body(body.toString()) - .asFile(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - assertThat(filledForm.getStatus()).isEqualTo(200); - - // check if all fields are filled - JSONObject fieldValues = null; - try { - File filled_out_pdf = new File(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - PDDocument pdf = Loader.loadPDF(filled_out_pdf); - fieldValues = getFieldValues(new FileInputStream(filled_out_pdf)); - } catch (IOException e) { - assertThat(false).isTrue(); - } - assertThat(fieldValues).isNotNull(); - // checkFormAnswersSS5Form(fieldValues); - // delete(fileId, "BLANK_FORM"); - TestUtils.logout(); - } - - @Test - public void fillApplicationQuestionsCaseWorkerTest() - throws IOException, GeneralSecurityException { - String caseWorkerUsername = "username1"; - String caseWorkerPassword = "password1"; - String clientUsername = "username2"; - String clientPassword = "password2"; - String organization = "org1"; - // Case worker - createUser() - .withUserType(UserType.Admin) - .withUsername(caseWorkerUsername) - .withPasswordToHash(caseWorkerPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - TestUtils.login(caseWorkerUsername, caseWorkerPassword); - // Client - createUser() - .withUserType(UserType.Client) - .withUsername(clientUsername) - .withPasswordToHash(clientPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - - File applicationPDF = new File(resourcesFolderPath + File.separator + "ss-5.pdf"); - String fileId = uploadFileAndGetFileId(applicationPDF, "BLANK_FORM"); - - JSONObject body = new JSONObject(); - body.put("applicationId", fileId); - body.put("clientUsername", clientUsername); - HttpResponse applicationsQuestionsResponse = - Unirest.post(TestUtils.getServerUrl() + "/get-application-questions") - .body(body.toString()) - .asString(); - JSONObject applicationsQuestionsResponseJSON = - TestUtils.responseStringToJSON(applicationsQuestionsResponse.getBody()); - assertThat(applicationsQuestionsResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - JSONObject formAnswers = getFormAnswersTestPDFForm(applicationsQuestionsResponseJSON); - // fill out form - body = new JSONObject(); - body.put("applicationId", fileId); - body.put("formAnswers", formAnswers); - body.put("clientUsername", clientUsername); - HttpResponse filledForm = - Unirest.post(TestUtils.getServerUrl() + "/fill-application") - .body(body.toString()) - .asFile(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - assertThat(filledForm.getStatus()).isEqualTo(200); - - // check if all fields are filled - JSONObject fieldValues = null; - try { - File filled_out_pdf = new File(resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"); - PDDocument pdf = Loader.loadPDF(filled_out_pdf); - fieldValues = getFieldValues(new FileInputStream(filled_out_pdf)); - } catch (IOException e) { - assertThat(false).isTrue(); - } - assertThat(fieldValues).isNotNull(); - // checkFormAnswersSS5Form(fieldValues); - // delete(fileId, "BLANK_FORM"); - TestUtils.logout(); - } - - // ------------------ UPLOAD SIGNED PDF TESTS ------------------------ //\ - - @Test - public void uploadSignedSSPDF() throws IOException, GeneralSecurityException { - String caseWorkerUsername = "username1"; - String caseWorkerPassword = "password1"; - String clientUsername = "username2"; - String clientPassword = "password2"; - String organization = "org1"; - // Case worker - createUser() - .withUserType(UserType.Admin) - .withUsername(caseWorkerUsername) - .withPasswordToHash(caseWorkerPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - TestUtils.login(caseWorkerUsername, caseWorkerPassword); - // Client - createUser() - .withUserType(UserType.Client) - .withUsername(clientUsername) - .withPasswordToHash(clientPassword) - .withOrgName(organization) - .buildAndPersist(userDao); - String filledApplicationPDFFilePath = - resourcesFolderPath + File.separator + "ss-5_filled_out.pdf"; - File filledApplicationPDF = new File(filledApplicationPDFFilePath); - String mimeTypePDF = Files.probeContentType(Path.of(filledApplicationPDFFilePath)); - String signatureImagePath = resourcesFolderPath + File.separator + "sample-signature.png"; - File signatureImage = new File(signatureImagePath); - String mimeTypeSignature = Files.probeContentType(Path.of(signatureImagePath)); - HttpResponse uploadSignedPDFResponse = - Unirest.post(TestUtils.getServerUrl() + "/upload-signed-pdf") - .header("Content-Disposition", "attachment") - .field("file", filledApplicationPDF, mimeTypePDF) - .field("pdfType", Collections.singleton(PDFType.COMPLETED_APPLICATION)) - .field("signature", signatureImage, mimeTypeSignature) - .field("clientUsername", clientUsername) - .asString(); - JSONObject responseJSON = TestUtils.responseStringToJSON(uploadSignedPDFResponse.getBody()); - System.out.println(responseJSON); - assertThat(responseJSON.getString("status")).isEqualTo("SUCCESS"); - TestUtils.logout(); - } - - // ------------------ GET METADATA TESTS ------------------------ // - - @Test // Test with title embedded in document - public void getPDFTitleTest1() throws IOException { - String fileName = "Application_for_a_Birth_Certificate.pdf"; - File applicationPDF = new File(resourcesFolderPath + File.separator + fileName); - InputStream pdfDocument = FileUtils.openInputStream(applicationPDF); - assertEquals( - "Application_for_a_Birth_Certificate.pdf", - PdfController.getPDFTitle(fileName, pdfDocument, PDFType.BLANK_FORM)); - } - - @Test // Test without any title in document - public void getPDFTitleTest2() throws IOException { - String fileName = "library-card-application.pdf"; - File applicationPDF = new File(resourcesFolderPath + File.separator + fileName); - InputStream pdfDocument = FileUtils.openInputStream(applicationPDF); - assertEquals(fileName, PdfController.getPDFTitle(fileName, pdfDocument, PDFType.BLANK_FORM)); - } -} diff --git a/src/test/PDFTest/ImageToPdfServiceIntegrationTests.java b/src/test/PDFTest/ImageToPdfServiceIntegrationTests.java deleted file mode 100644 index deef7343..00000000 --- a/src/test/PDFTest/ImageToPdfServiceIntegrationTests.java +++ /dev/null @@ -1,164 +0,0 @@ -package PDFTest; - -import Config.DeploymentLevel; -import Database.User.UserDao; -import Database.User.UserDaoFactory; -import TestUtils.TestUtils; -import User.User; -import User.UserType; -import File.IdCategoryType; -import kong.unirest.HttpResponse; -import kong.unirest.Unirest; -import org.apache.commons.io.FileUtils; -import org.json.JSONObject; -import org.junit.*; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import static PDFTest.PDFTestUtils.*; -import static TestUtils.EntityFactory.createUser; -import static TestUtils.TestUtils.assertPDFEquals; -import static org.assertj.core.api.Assertions.assertThat; - -public class ImageToPdfServiceIntegrationTests { - private UserDao userDao; - - @BeforeClass - public static void setUp() { - TestUtils.startServer(); - } - - @Before - public void initialize() { - this.userDao = UserDaoFactory.create(DeploymentLevel.TEST); - } - - @After - public void reset() { - if(this.userDao != null) { - this.userDao.clear(); - } - TestUtils.logout(); - } - - @AfterClass - public static void tearDown() { - TestUtils.tearDownTestDB(); - } - - @Test - public void uploadPNGImageToPDFTest() throws IOException { - File expectedOutputFile = new File(resourcesFolderPath + File.separator + "1_converted.pdf"); - InputStream expectedOutputFileStream = FileUtils.openInputStream(expectedOutputFile); - - User user = - createUser() - .withUserType(UserType.Client) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File file = new File(resourcesFolderPath + File.separator + "1.png"); - HttpResponse uploadResponse = - Unirest.post(TestUtils.getServerUrl() + "/upload") - .field("pdfType", "IDENTIFICATION_DOCUMENT") - .header("Content-Disposition", "attachment") - .field("file", file, "image/jpeg") - .field("idCategory", IdCategoryType.OTHER.toString()) - .asString(); - - JSONObject uploadResponseJSON = TestUtils.responseStringToJSON(uploadResponse.getBody()); - assertThat(uploadResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - String fileId = getPDFFileId(); - File downloadedPDF = downloadPDF(fileId, "IDENTIFICATION_DOCUMENT"); - InputStream downloadedPDFInputStream = FileUtils.openInputStream(downloadedPDF); - assertPDFEquals(expectedOutputFileStream, downloadedPDFInputStream); - - TestUtils.logout(); - } - - @Test - public void uploadImageJPEGToPDFTest() throws IOException { - File expectedOutputFile = new File(resourcesFolderPath + File.separator + "veteran-id-card-vic_converted.pdf"); - InputStream expectedOutputFileStream = FileUtils.openInputStream(expectedOutputFile); - - User user = - createUser() - .withUserType(UserType.Client) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File file = new File(resourcesFolderPath + File.separator + "veteran-id-card-vic.jpg"); - HttpResponse uploadResponse = - Unirest.post(TestUtils.getServerUrl() + "/upload") - .field("pdfType", "IDENTIFICATION_DOCUMENT") - .header("Content-Disposition", "attachment") - .field("file", file, "image/jpeg") - .field("idCategory", IdCategoryType.VETERAN_ID_CARD.toString()) - .asString(); - - JSONObject uploadResponseJSON = TestUtils.responseStringToJSON(uploadResponse.getBody()); - assertThat(uploadResponseJSON.getString("status")).isEqualTo("SUCCESS"); - - String fileId = getPDFFileId(); - File downloadedPDF = downloadPDF(fileId, "IDENTIFICATION_DOCUMENT"); - InputStream downloadedPDFInputStream = FileUtils.openInputStream(downloadedPDF); - assertPDFEquals(expectedOutputFileStream, downloadedPDFInputStream); - - TestUtils.logout(); - } - - @Test - public void uploadImageJPEGToPDFInvalidIdCategoryTest() { - User user = - createUser() - .withUserType(UserType.Client) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File file = new File(resourcesFolderPath + File.separator + "veteran-id-card-vic.jpg"); - HttpResponse uploadResponse = - Unirest.post(TestUtils.getServerUrl() + "/upload") - .field("pdfType", "IDENTIFICATION_DOCUMENT") - .header("Content-Disposition", "attachment") - .field("file", file, "image/jpeg") - .asString(); - - JSONObject uploadResponseJSON = TestUtils.responseStringToJSON(uploadResponse.getBody()); - assertThat(uploadResponseJSON.getString("status")).isEqualTo("INVALID_ID_CATEGORY"); - - TestUtils.logout(); - } - - @Test - public void uploadInvalidImageToPDFTest() { - User user = - createUser() - .withUserType(UserType.Client) - .withUsername(username) - .withPasswordToHash(password) - .buildAndPersist(userDao); - TestUtils.login(username, password); - - File file = new File(resourcesFolderPath + File.separator + "job_description.docx"); - HttpResponse uploadResponse = - Unirest.post(TestUtils.getServerUrl() + "/upload") - .field("pdfType", "IDENTIFICATION_DOCUMENT") - .header("Content-Disposition", "attachment") - .field("file", file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") - .field("idCategory", IdCategoryType.OTHER.toString()) - .asString(); - - JSONObject uploadResponseJSON = TestUtils.responseStringToJSON(uploadResponse.getBody()); - assertThat(uploadResponseJSON.getString("status")).isEqualTo("INVALID_PDF"); - TestUtils.logout(); - } -} diff --git a/src/test/PDFTest/PDFControllerUnitTests.java b/src/test/PDFTest/PDFControllerUnitTests.java deleted file mode 100644 index 479cab86..00000000 --- a/src/test/PDFTest/PDFControllerUnitTests.java +++ /dev/null @@ -1,616 +0,0 @@ -// package PDFTest; -// -// import TestUtils.TestUtils; -// import org.apache.pdfbox.cos.COSName; -// import org.apache.pdfbox.io.IOUtils; -// import org.apache.pdfbox.pdmodel.PDDocument; -// import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; -// import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions; -// import org.apache.pdfbox.pdmodel.interactive.digitalsignature.visible.PDVisibleSigProperties; -// import org.apache.pdfbox.pdmodel.interactive.digitalsignature.visible.PDVisibleSignDesigner; -// import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField; -// import org.json.JSONArray; -// import org.json.JSONObject; -// import org.junit.Assert; -// import org.junit.Test; -// -// import java.io.File; -// import java.io.FileInputStream; -// import java.io.IOException; -// import java.io.InputStream; -// import java.util.*; -// -// import static TestUtils.TestUtils.getFieldValues; -// -// public class PdfControllerUnitTests { -// -// // Get subset of fields of type fieldType -// private List getFieldsOfType(List fieldsJSON, String fieldType) { -// List newFieldsJSON = new LinkedList<>(); -// for (JSONObject field : fieldsJSON) { -// if (field.getString("fieldType").equals(fieldType)) { -// newFieldsJSON.add(field); -// } -// } -// return newFieldsJSON; -// } -// -// private JSONObject createFieldJSON( -// String fieldName, String fieldType, String[] fieldValueOptions) { -// JSONArray fieldValueOptionsJSON = new JSONArray(); -// for (String fieldValueOption : fieldValueOptions) { -// fieldValueOptionsJSON.put(fieldValueOption); -// } -// return (new JSONObject() -// .put("fieldName", fieldName) -// .put("fieldType", fieldType) -// .put("fieldValueOptions", fieldValueOptionsJSON.toString()) -// .put("fieldMatchedDBName", "") -// .put("fieldMatchedDBVariable", "") -// .put("fieldQuestion", "Please Enter Your " + fieldName)); -// } -// -// class JSONFieldComparator implements Comparator { -// public int compare(JSONObject a, JSONObject b) { -// return (a.getString("fieldName").compareTo(b.getString("fieldName"))); -// } -// } -// -// @Test(expected = IOException.class) -// public void getFieldInformationNullFileTest() throws IOException { -// File pdfInput = new File(""); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// pdfDocument.close(); -// } -// -// @Test(expected = IllegalArgumentException.class) -// public void getFieldInformationNullPDFDocumentTest() throws IOException { -// List fieldsJSON = getFieldInformation(null); -// } -// -// @Test -// // NOTE: We need to fix the file so that the buttons are radio -// public void getFieldInformationValidValuesTest1() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Make sure field names are correct -// for (JSONObject field : fieldsJSON) { -// -// // Not Editable -// Assert.assertNotEquals("", field.getString("fieldName")); -// Assert.assertNotEquals("", field.getString("fieldType")); -// Assert.assertNotEquals(null, field.getJSONArray("fieldValueOptions").toString()); -// -// // Editable -// Assert.assertNotEquals("", field.getString("fieldQuestion")); -// Assert.assertEquals("", field.getString("fieldMatchedDBName")); -// Assert.assertEquals("", field.getString("fieldMatchedDBVariable")); -// -// // Is valid fieldType -// Set validFieldTypes = TestUtils.validFieldTypes; -// Assert.assertTrue(validFieldTypes.contains(field.getString("fieldType"))); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void getFieldInformationTextFieldTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {}; -// correctFieldsJSON.add(createFieldJSON("Name", "TextField", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("Title", "TextField", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("Address", "TextField", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("A different address", "TextField", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("currentdate_af_date", "TextField", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "TextField"); -// testFieldsJSON.sort(new JSONFieldComparator()); -// Iterator testFieldsJSONIterator = testFieldsJSON.iterator(); -// -// // Check Not Editable Fields are correct -// while (testFieldsJSONIterator.hasNext() || correctFieldIterator.hasNext()) { -// JSONObject field = testFieldsJSONIterator.next(); -// JSONObject correctField = correctFieldIterator.next(); -// -// // Change to equals for GSON -// Assert.assertEquals(correctField.getString("fieldName"), field.getString("fieldName")); -// Assert.assertEquals(correctField.getString("fieldType"), field.getString("fieldType")); -// Assert.assertEquals( -// correctField.getString("fieldValueOptions"), -// field.getJSONArray("fieldValueOptions").toString()); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void getFieldInformationComboBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {"Choice1", "Choice2", "Choice3"}; -// correctFieldsJSON.add(createFieldJSON("Dropdown", "ComboBox", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "ComboBox"); -// testFieldsJSON.sort(new JSONFieldComparator()); -// Iterator testFieldsJSONIterator = testFieldsJSON.iterator(); -// -// // Check Not Editable Fields are correct -// while (testFieldsJSONIterator.hasNext() || correctFieldIterator.hasNext()) { -// JSONObject field = testFieldsJSONIterator.next(); -// JSONObject correctField = correctFieldIterator.next(); -// -// // Change to equals for GSON -// Assert.assertEquals(correctField.getString("fieldName"), field.getString("fieldName")); -// Assert.assertEquals(correctField.getString("fieldType"), field.getString("fieldType")); -// Assert.assertEquals( -// correctField.getString("fieldValueOptions"), -// field.getJSONArray("fieldValueOptions").toString()); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void getFieldInformationListBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {"Choice1", "Choice2", "Choice3"}; -// correctFieldsJSON.add(createFieldJSON("Combobox", "ListBox", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "ListBox"); -// testFieldsJSON.sort(new JSONFieldComparator()); -// Iterator testFieldsJSONIterator = testFieldsJSON.iterator(); -// -// // Check Not Editable Fields are correct -// while (testFieldsJSONIterator.hasNext() || correctFieldIterator.hasNext()) { -// JSONObject field = testFieldsJSONIterator.next(); -// JSONObject correctField = correctFieldIterator.next(); -// -// // Change to equals for GSON -// Assert.assertEquals(correctField.getString("fieldName"), field.getString("fieldName")); -// Assert.assertEquals(correctField.getString("fieldType"), field.getString("fieldType")); -// Assert.assertEquals( -// correctField.getString("fieldValueOptions"), -// field.getJSONArray("fieldValueOptions").toString()); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void getFieldInformationCheckBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {"Yes"}; -// correctFieldsJSON.add(createFieldJSON("Chicken", "CheckBox", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("Vegetables", "CheckBox", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("Ribeye Steaks", "CheckBox", fieldValueOptions)); -// correctFieldsJSON.add(createFieldJSON("Tomatoes", "CheckBox", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "CheckBox"); -// testFieldsJSON.sort(new JSONFieldComparator()); -// Iterator testFieldsJSONIterator = testFieldsJSON.iterator(); -// -// // Check Not Editable Fields are correct -// while (testFieldsJSONIterator.hasNext() || correctFieldIterator.hasNext()) { -// JSONObject field = testFieldsJSONIterator.next(); -// JSONObject correctField = correctFieldIterator.next(); -// -// // Change to equals for GSON -// Assert.assertEquals(correctField.getString("fieldName"), field.getString("fieldName")); -// Assert.assertEquals(correctField.getString("fieldType"), field.getString("fieldType")); -// Assert.assertEquals( -// correctField.getString("fieldValueOptions"), -// field.getJSONArray("fieldValueOptions").toString()); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void getFieldInformationRadioButtonTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {"Yes", "No", "Maybe"}; -// correctFieldsJSON.add(createFieldJSON("Radiobuttons", "RadioButton", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "RadioButton"); -// testFieldsJSON.sort(new JSONFieldComparator()); -// Iterator testFieldsJSONIterator = testFieldsJSON.iterator(); -// -// // Check Not Editable Fields are correct -// while (testFieldsJSONIterator.hasNext() || correctFieldIterator.hasNext()) { -// JSONObject field = testFieldsJSONIterator.next(); -// JSONObject correctField = correctFieldIterator.next(); -// -// // Change to equals for GSON -// Assert.assertEquals(correctField.getString("fieldName"), field.getString("fieldName")); -// Assert.assertEquals(correctField.getString("fieldType"), field.getString("fieldType")); -// Assert.assertEquals( -// correctField.getString("fieldValueOptions"), -// field.getJSONArray("fieldValueOptions").toString()); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsBasicTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// JSONObject formAnswers = new JSONObject(); -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsTextFieldTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// JSONObject formAnswers = new JSONObject(); -// formAnswers.put("Name", "Steffen"); -// formAnswers.put("Title", "Play"); -// formAnswers.put("Address", "123 Market Street"); -// formAnswers.put("A different address", "321 Broad Street"); -// formAnswers.put("currentdate_af_date", "07/07/2020"); -// -// JSONObject correctFieldValues = new JSONObject(); -// correctFieldValues.put("Name", "Steffen"); -// correctFieldValues.put("Title", "Play"); -// correctFieldValues.put("Address", "123 Market Street"); -// correctFieldValues.put("A different address", "321 Broad Street"); -// correctFieldValues.put("currentdate_af_date", "07/07/2020"); -// -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsCheckBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// JSONObject formAnswers = new JSONObject(); -// formAnswers.put("Chicken", true); -// formAnswers.put("Vegetables", false); -// formAnswers.put("Ribeye Steaks", false); -// formAnswers.put("Tomatoes", true); -// -// JSONObject correctFieldValues = new JSONObject(); -// correctFieldValues.put("Chicken", "Yes"); -// correctFieldValues.put("Vegetables", "Off"); -// correctFieldValues.put("Ribeye Steaks", "Off"); -// correctFieldValues.put("Tomatoes", "Yes"); -// -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsRadioButtonTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// JSONObject formAnswers = new JSONObject(); -// formAnswers.put("Radiobuttons", "Yes"); -// -// JSONObject correctFieldValues = new JSONObject(); -// correctFieldValues.put("Radiobuttons", "Yes"); -// -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// formAnswers.put("Radiobuttons", "No"); -// correctFieldValues.put("Radiobuttons", "No"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// pdfDocument = PDDocument.load(pdfInput); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// formAnswers.put("Radiobuttons", "Maybe"); -// correctFieldValues.put("Radiobuttons", "Maybe"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// pdfDocument = PDDocument.load(pdfInput); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsListBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// JSONObject formAnswers = new JSONObject(); -// formAnswers.put("Dropdown", "Choice1"); -// -// JSONObject correctFieldValues = new JSONObject(); -// correctFieldValues.put("Dropdown", "[Choice1]"); -// -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// formAnswers.put("Dropdown", "Choice2"); -// correctFieldValues.put("Dropdown", "[Choice2]"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// formAnswers.put("Dropdown", "Choice3"); -// correctFieldValues.put("Dropdown", "[Choice3]"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// } -// -// @Test -// public void fillFieldsComboBoxTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// JSONObject formAnswers = new JSONObject(); -// JSONArray choices = new JSONArray(); -// choices.put("Choice1"); -// formAnswers.put("Combobox", choices); -// -// JSONObject correctFieldValues = new JSONObject(); -// correctFieldValues.put("Combobox", "[Choice1]"); -// -// InputStream completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// JSONObject fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// choices = new JSONArray(); -// choices.put("Choice2"); -// formAnswers.put("Combobox", choices); -// correctFieldValues.put("Combobox", "[Choice2]"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// pdfDocument.close(); -// pdfDocument = PDDocument.load(pdfInput); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// choices = new JSONArray(); -// choices.put("Choice1"); -// choices.put("Choice2"); -// formAnswers.put("Combobox", choices); -// correctFieldValues.put("Combobox", "[Choice1, Choice2]"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// pdfDocument.close(); -// pdfDocument = PDDocument.load(pdfInput); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// -// choices = new JSONArray(); -// choices.put("Choice1"); -// choices.put("Choice2"); -// choices.put("Choice3"); -// formAnswers.put("Combobox", choices); -// correctFieldValues.put("Combobox", "[Choice1, Choice2, Choice3]"); -// -// pdfInput = new File("src/test/resources/testpdf.pdf"); -// pdfDocument.close(); -// pdfDocument = PDDocument.load(pdfInput); -// completedPDF = fillFields(new FileInputStream(pdfInput), formAnswers); -// fieldValues = getFieldValues(completedPDF); -// -// // We test that all the fields in correctFields have the right value -// for (String key : correctFieldValues.keySet()) { -// Assert.assertEquals(correctFieldValues.getString(key), fieldValues.getString(key)); -// } -// pdfDocument.close(); -// } -// -// @Test -// public void fillFieldsSignatureFieldTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// InputStream imageStream = new FileInputStream("src/test/resources/first-love.png"); // PNG -// PDDocument pdfDocument = PDDocument.load(pdfInput); -// -// PDVisibleSignDesigner visibleSignDesigner = new PDVisibleSignDesigner(imageStream); -// visibleSignDesigner.zoom(0); -// PDVisibleSigProperties visibleSigProperties = -// new PDVisibleSigProperties() -// .visualSignEnabled(true) -// .setPdVisibleSignature(visibleSignDesigner); -// visibleSigProperties.buildSignature(); -// -// PDSignature signature = new PDSignature(); -// signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); -// signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); -// signature.setName("Example Name1"); -// signature.setLocation("Philadelphia, PA"); -// signature.setReason("Application"); -// signature.setSignDate(Calendar.getInstance()); -// -// SignatureOptions signatureOptions = new SignatureOptions(); -// signatureOptions.setVisualSignature(visibleSigProperties.getVisibleSignature()); -// PDSignatureField signatureField = -// (PDSignatureField) pdfDocument.getDocumentCatalog().getAcroForm().getField("Signature"); -// signatureField.setValue(signature); -// pdfDocument.addSignature(signature, signatureOptions); -// -// PDSignature signatureDocument = signatureField.getSignature(); -// Assert.assertEquals(signature.getFilter(), signatureDocument.getFilter()); -// Assert.assertEquals(signature.getSubFilter(), signature.getSubFilter()); -// Assert.assertEquals(signature.getName(), signatureDocument.getName()); -// Assert.assertEquals(signature.getLocation(), signatureDocument.getLocation()); -// Assert.assertEquals(signature.getReason(), signatureDocument.getReason()); -// Assert.assertEquals(signature.getSignDate(), signatureDocument.getSignDate()); -// Assert.assertEquals( -// signature.getCOSObject().getItem(COSName.CONTENTS), -// signatureDocument.getCOSObject().getItem((COSName.CONTENTS))); -// -// IOUtils.closeQuietly(signatureOptions); -// pdfDocument.close(); -// } -// -// @Test -// // NOTE: We need to fix the file so that the buttons are radio -// public void getFieldInformationValidValuesTest2() throws IOException { -// File pdfInput = new File("src/test/resources/ss-5.pdf"); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Make sure field names are correct -// for (JSONObject field : fieldsJSON) { -// // Not Editable -// Assert.assertNotEquals("", field.getString("fieldName")); -// Assert.assertNotEquals("", field.getString("fieldType")); -// Assert.assertNotEquals(null, field.getJSONArray("fieldValueOptions")); -// -// // Editable -// Assert.assertNotEquals("", field.getString("fieldQuestion")); -// Assert.assertEquals("", field.getString("fieldMatchedDBName")); -// Assert.assertEquals("", field.getString("fieldMatchedDBVariable")); -// -// // Is valid fieldType -// Set validFieldTypes = TestUtils.validFieldTypes; -// Assert.assertTrue(validFieldTypes.contains(field.getString("fieldType"))); -// } -// } -// -// @Test -// // NOTE: We need to fix the file so that the buttons are radio -// public void getFieldInformationValidValuesTest3() throws IOException { -// File pdfInput = new File("src/test/resources/Application_for_a_Birth_Certificate.pdf"); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Make sure field names are correct -// for (JSONObject field : fieldsJSON) { -// // Not Editable -// Assert.assertNotEquals("", field.getString("fieldName")); -// Assert.assertNotEquals("", field.getString("fieldType")); -// Assert.assertNotEquals(null, field.getJSONArray("fieldValueOptions")); -// -// // Editable -// Assert.assertNotEquals("", field.getString("fieldQuestion")); -// Assert.assertEquals("", field.getString("fieldMatchedDBName")); -// Assert.assertEquals("", field.getString("fieldMatchedDBVariable")); -// -// // Is valid fieldType -// Set validFieldTypes = TestUtils.validFieldTypes; -// Assert.assertTrue(validFieldTypes.contains(field.getString("fieldType"))); -// } -// } -// -// @Test -// public void getFieldInformationPushButtonTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "PushButton"); -// Assert.assertEquals(0, testFieldsJSON.size()); -// } -// -// @Test -// public void getFieldInformationSignatureFieldTest() throws IOException { -// File pdfInput = new File("src/test/resources/testpdf.pdf"); -// List fieldsJSON = getFieldInformation(new FileInputStream(pdfInput)); -// -// // Set up correct field names and questions -// List correctFieldsJSON = new LinkedList<>(); -// String[] fieldValueOptions = {}; -// correctFieldsJSON.add(createFieldJSON("Signature", "SignatureField", fieldValueOptions)); -// correctFieldsJSON.sort(new JSONFieldComparator()); -// Iterator correctFieldIterator = correctFieldsJSON.iterator(); -// -// // Get Only Fields Needed for This Test -// List testFieldsJSON = getFieldsOfType(fieldsJSON, "SignatureField"); -// Assert.assertEquals(0, testFieldsJSON.size()); -// } -// } diff --git a/src/test/PDFTest/PDFV2Test/FillPDFServiceV2UnitTests.java b/src/test/PDFTest/PDFV2Test/FillPDFServiceV2UnitTests.java index a5676dd5..dd612c94 100644 --- a/src/test/PDFTest/PDFV2Test/FillPDFServiceV2UnitTests.java +++ b/src/test/PDFTest/PDFV2Test/FillPDFServiceV2UnitTests.java @@ -162,7 +162,7 @@ public void fillPDFServiceNullSignatureStream() { new FillPDFServiceV2( fileDao, formDao, clientUserParams, fillFileParams, encryptionController); Message response = fillService.executeAndGetResponse(); - assertEquals(PdfMessage.SERVER_ERROR, response); + assertEquals(PdfMessage.SUCCESS, response); // Filling PDF with null signature stream is now allowed } @Test diff --git a/src/test/PDFTest/PDFV2Test/GetQuestionsPDFServiceV2UnitTests.java b/src/test/PDFTest/PDFV2Test/GetQuestionsPDFServiceV2UnitTests.java index 14e0bff2..b1eee635 100644 --- a/src/test/PDFTest/PDFV2Test/GetQuestionsPDFServiceV2UnitTests.java +++ b/src/test/PDFTest/PDFV2Test/GetQuestionsPDFServiceV2UnitTests.java @@ -55,7 +55,6 @@ public static void start() { @Before public void initialize() throws InterruptedException { - Thread.sleep(1000); this.fileDao = FileDaoFactory.create(DeploymentLevel.TEST); this.formDao = FormDaoFactory.create(DeploymentLevel.TEST); this.userDao = UserDaoFactory.create(DeploymentLevel.TEST); diff --git a/src/test/PDFTest/PDFV2Test/UploadAnnotatedPDFServiceUnitTests.java b/src/test/PDFTest/PDFV2Test/UploadAnnotatedPDFServiceUnitTests.java index 43db868c..3baf3e17 100644 --- a/src/test/PDFTest/PDFV2Test/UploadAnnotatedPDFServiceUnitTests.java +++ b/src/test/PDFTest/PDFV2Test/UploadAnnotatedPDFServiceUnitTests.java @@ -41,9 +41,7 @@ public class UploadAnnotatedPDFServiceUnitTests { @BeforeClass public static void start() throws InterruptedException { - Thread.sleep(3000); TestUtils.startServer(); - Thread.sleep(3000); } @Before diff --git a/src/test/ProductionAPITest/ProductionControllerIntegrationTests.java b/src/test/ProductionAPITest/ProductionControllerIntegrationTests.java index 356ff433..1238905e 100644 --- a/src/test/ProductionAPITest/ProductionControllerIntegrationTests.java +++ b/src/test/ProductionAPITest/ProductionControllerIntegrationTests.java @@ -60,12 +60,6 @@ public static void setUp() throws ValidationException { @Before public void login() { TestUtils.login("devYMCA", "devYMCA123"); - try { - TimeUnit.SECONDS.sleep(1); // this looks super jank but basically we are running into concurrency problems - // if we login too fast because the login call is asynchronous because we are using unirest - } catch (InterruptedException e) { - e.printStackTrace(); - } } @After @@ -139,8 +133,8 @@ public void createUserWithInvalidProperties() { .body(postBody.toString()) .asString(); - assertThat(createUserResponse.getStatus()).isEqualTo(400); - assertThat(createUserResponse.getBody()).contains("Couldn't deserialize body to User"); + assertThat(createUserResponse.getStatus()).isEqualTo(500); + assertThat(createUserResponse.getBody()).contains("Server Error"); MongoDatabase testDB = MongoConfig.getDatabase(DeploymentLevel.TEST); var dbUsers = testDB.getCollection("user", User.class); @@ -319,9 +313,9 @@ public void updateUserWithInvalidProperties() { Unirest.patch(TestUtils.getServerUrl() + "/users/" + username) .body(updateBody.toString()) .asString(); - - assertThat(updateResponse.getStatus()).isEqualTo(400); - assertThat(updateResponse.getBody()).contains("Couldn't deserialize body to UserUpdateRequest"); + + assertThat(updateResponse.getStatus()).isEqualTo(500); + assertThat(updateResponse.getBody()).contains("Server Error"); } @Test @@ -378,8 +372,8 @@ public void createOrganizationWithInvalidProperties() { .body(postBody.toString()) .asString(); - assertThat(createOrganizationResponse.getStatus()).isEqualTo(400); - assertThat(createOrganizationResponse.getBody()).contains("Couldn't deserialize body to Organization"); + assertThat(createOrganizationResponse.getStatus()).isEqualTo(500); + assertThat(createOrganizationResponse.getBody()).contains("Server Error"); MongoDatabase testDB = MongoConfig.getDatabase(DeploymentLevel.TEST); var dbOrganizations = testDB.getCollection("organization", Organization.class); @@ -551,8 +545,8 @@ public void updateOrganizationWithInvalidProperties() { .body(updateBody.toString()) .asString(); - assertThat(updateResponse.getStatus()).isEqualTo(400); - assertThat(updateResponse.getBody()).contains("Couldn't deserialize body to OrganizationUpdateRequest"); + assertThat(updateResponse.getStatus()).isEqualTo(500); + assertThat(updateResponse.getBody()).contains("Server Error"); } @Test diff --git a/src/test/TestUtils/TestUtils.java b/src/test/TestUtils/TestUtils.java index 41b99cef..b160f3c6 100644 --- a/src/test/TestUtils/TestUtils.java +++ b/src/test/TestUtils/TestUtils.java @@ -3,6 +3,7 @@ import Config.AppConfig; import Config.DeploymentLevel; import Config.MongoConfig; +import Config.SessionConfig; import Organization.Organization; import Security.EncryptionTools; import Security.EncryptionUtils; @@ -81,6 +82,8 @@ public static void stopServer() { app.stop(); app = null; } + // Reset session handler to prevent state leakage between tests + SessionConfig.resetSessionHandler(); } public static String getServerUrl() { @@ -806,6 +809,12 @@ public static JSONObject responseStringToJSON(String response) { if (v instanceof String str) { String inner = stripBomAndWhitespace(str); if (inner.startsWith("{")) return new JSONObject(inner); + if (str.equals("Server Error") || str.equals("Internal Server Error")){ + throw new IllegalStateException("Server Error"); + } + if (str.startsWith("Endpoint POST")){ + return new JSONObject(); + } throw new JSONException("Quoted string does not contain an object: " + preview(inner)); } throw new JSONException("Expected object; got " + v.getClass().getSimpleName() + ": " + preview(s)); diff --git a/src/test/UserTest/UserControllerIntegrationTest.java b/src/test/UserTest/UserControllerIntegrationTest.java index 83a5c802..9a37eac5 100644 --- a/src/test/UserTest/UserControllerIntegrationTest.java +++ b/src/test/UserTest/UserControllerIntegrationTest.java @@ -6,9 +6,10 @@ import kong.unirest.HttpResponse; import kong.unirest.Unirest; import org.json.JSONObject; +import org.junit.After; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.jupiter.api.AfterAll; public class UserControllerIntegrationTest { @@ -18,7 +19,15 @@ public static void setUp() { TestUtils.setUpTestDB(); } - @AfterAll + @After + public void tearDownEachTest() { + try { + TestUtils.logout(); + } catch (Exception ignored) { + } + } + + @AfterClass public static void tearDown() { TestUtils.tearDownTestDB(); } diff --git a/src/test/resources/ss-5_filled_out_test_download.pdf b/src/test/resources/ss-5_filled_out_test_download.pdf index 1beec059..69a46947 100644 Binary files a/src/test/resources/ss-5_filled_out_test_download.pdf and b/src/test/resources/ss-5_filled_out_test_download.pdf differ diff --git a/src/test/resources/ss-5_filled_out_test_fill.pdf b/src/test/resources/ss-5_filled_out_test_fill.pdf index dcff95c6..29fc5dc6 100644 Binary files a/src/test/resources/ss-5_filled_out_test_fill.pdf and b/src/test/resources/ss-5_filled_out_test_fill.pdf differ