From 2564995bf97583744b41d616e26eeffada92af86 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 12:57:25 +0100 Subject: [PATCH 01/11] First Unit Tests to checkout on SonarCloud --- pom.xml | 19 ++++ .../service/license/LicenseActivation.java | 3 + .../service/encryption/EncryptionTest.java | 38 ++++++++ .../license/LicenseActivationTest.java | 94 +++++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 src/test/java/model/service/encryption/EncryptionTest.java create mode 100644 src/test/java/model/service/license/LicenseActivationTest.java diff --git a/pom.xml b/pom.xml index 751c7dc..986c7bb 100644 --- a/pom.xml +++ b/pom.xml @@ -81,6 +81,25 @@ javax.json 1.1.4 + + junit + junit + 4.13.2 + test + + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + test + + + org.mockito + mockito-core + 5.3.1 + test + diff --git a/src/main/java/model/service/license/LicenseActivation.java b/src/main/java/model/service/license/LicenseActivation.java index a1a43c9..4b6ed54 100644 --- a/src/main/java/model/service/license/LicenseActivation.java +++ b/src/main/java/model/service/license/LicenseActivation.java @@ -6,6 +6,9 @@ public class LicenseActivation implements LicenseActivationInterface { DAOLicense daoLicense = new DAOLicense(); + public void setDAOLicense(DAOLicense daoLicense) { + this.daoLicense = daoLicense; + } public License getLicense(String code) { return daoLicense.getLicenseByCode(code); } diff --git a/src/test/java/model/service/encryption/EncryptionTest.java b/src/test/java/model/service/encryption/EncryptionTest.java new file mode 100644 index 0000000..ebb6c59 --- /dev/null +++ b/src/test/java/model/service/encryption/EncryptionTest.java @@ -0,0 +1,38 @@ +package model.service.encryption; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.*; + + +public class EncryptionTest { + + @Test + public void testEncryptPassword() { + Encryption encryption = new Encryption(); + String plainTextPassword = "password"; + + // Ensure that the encrypted password is not null or empty + String encryptedPassword = encryption.encryptPassword(plainTextPassword); + assertNotNull(encryptedPassword); + assertFalse(encryptedPassword.isEmpty()); + + // Ensure that each encryption of the same password produces different results + String secondEncryptedPassword = encryption.encryptPassword(plainTextPassword); + assertNotEquals(encryptedPassword, secondEncryptedPassword); + } + + @Test + public void testVerifyPassword() { + Encryption encryption = new Encryption(); + String plainTextPassword = "password"; + String hashedPassword = encryption.encryptPassword(plainTextPassword); + + // Ensure that the password is verified correctly + assertTrue(encryption.verifyPassword(plainTextPassword, hashedPassword)); + + // Ensure that an incorrect password is not verified + String incorrectPassword = "wrongpassword"; + assertFalse(encryption.verifyPassword(incorrectPassword, hashedPassword)); + } +} diff --git a/src/test/java/model/service/license/LicenseActivationTest.java b/src/test/java/model/service/license/LicenseActivationTest.java new file mode 100644 index 0000000..1c8984c --- /dev/null +++ b/src/test/java/model/service/license/LicenseActivationTest.java @@ -0,0 +1,94 @@ +package model.service.license; + +import model.DAO.DAOLicense; +import org.junit.jupiter.api.Test; +import model.service.license.LicenseActivation; +import model.entity.License; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class LicenseActivationTest { + + @Test + void testGetLicense() { + // Mock the DAOLicense class + DAOLicense daoLicenseMock = mock(DAOLicense.class); + + // Set up the LicenseActivation class with the mocked DAO + LicenseActivation licenseActivation = new LicenseActivation(); + licenseActivation.setDAOLicense(daoLicenseMock); + + // Create a sample license + License sampleLicense = new License(); + sampleLicense.setSequence("1234"); + sampleLicense.setIdUser(1); + + // Mock the behavior of the DAO method + when(daoLicenseMock.getLicenseByCode(anyString())).thenReturn(sampleLicense); + + // Test the getLicense method + License resultLicense = licenseActivation.getLicense("sampleCode"); + assertNotNull(resultLicense); + assertEquals(sampleLicense, resultLicense); + } + + @Test + void testIsActivable() { + LicenseActivation licenseActivation = new LicenseActivation(); + + // Test with an active license + License activeLicense = new License(); + activeLicense.setActive(true); + assertFalse(licenseActivation.isActivable(activeLicense)); + + // Test with an inactive license + License inactiveLicense = new License(); + inactiveLicense.setActive(false); + assertTrue(licenseActivation.isActivable(inactiveLicense)); + + // Test with a null license + assertFalse(licenseActivation.isActivable(null)); + } + + @Test + void testIsForTherapist() { + LicenseActivation licenseActivation = new LicenseActivation(); + + // Test with a valid therapist license + License therapistLicense = new License(); + therapistLicense.setSequence("1234"); + therapistLicense.setIdUser(1); + assertEquals(1, licenseActivation.isForTherapist(therapistLicense)); + + // Test with an invalid therapist license + License invalidTherapistLicense = new License(); + invalidTherapistLicense.setSequence("123"); + invalidTherapistLicense.setIdUser(2); + assertEquals(0, licenseActivation.isForTherapist(invalidTherapistLicense)); + + // Test with a null license + assertEquals(0, licenseActivation.isForTherapist(null)); + } + + @Test + void testActivate() { + // Mock the DAOLicense class + DAOLicense daoLicenseMock = mock(DAOLicense.class); + + // Set up the LicenseActivation class with the mocked DAO + LicenseActivation licenseActivation = new LicenseActivation(); + licenseActivation.setDAOLicense(daoLicenseMock); + + // Create a sample license + License sampleLicense = new License(); + sampleLicense.setSequence("1234"); + sampleLicense.setIdUser(1); + + // Test the activate method + licenseActivation.activate(sampleLicense, 1); + + // Verify that the DAO's activate method was called with the correct parameters + verify(daoLicenseMock, times(1)).activate(eq(sampleLicense), eq(1)); + } +} From 3719ed5009f1895f917c00b94826c8e86c385941 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 13:31:37 +0100 Subject: [PATCH 02/11] Added mockito, jupiter and plugins in pom --- pom.xml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pom.xml b/pom.xml index 986c7bb..7857191 100644 --- a/pom.xml +++ b/pom.xml @@ -110,6 +110,36 @@ maven-war-plugin 3.4.0 + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + ${surefireArgLine} + + + + + org.jacoco + jacoco-maven-plugin + 0.8.7 + + + prepare-agent + + prepare-agent + + + + report + verify + + report + + + + From bf1edcb3116346843eb04c8df052a5c55ae24e12 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 17:58:09 +0100 Subject: [PATCH 03/11] working pom.xml for JaCoCo report --- pom.xml | 47 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index 7857191..9ced475 100644 --- a/pom.xml +++ b/pom.xml @@ -64,12 +64,6 @@ 3.1.0 - - javax.servlet - javax.servlet-api - 3.1.0 - - javax.json javax.json-api @@ -88,12 +82,6 @@ test - - org.junit.jupiter - junit-jupiter-engine - 5.9.2 - test - org.mockito mockito-core @@ -105,6 +93,18 @@ + + org.apache.maven.plugins + maven-site-plugin + 3.12.1 + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.2.1 + + org.apache.maven.plugins maven-war-plugin @@ -116,7 +116,7 @@ 2.22.2 - ${surefireArgLine} + -Xmx1024M ${argLine} @@ -136,7 +136,28 @@ verify report + report-integration + + + + jacoco-check + + check + + + + PACKAGE + + + LINE + COVEREDRATIO + 0.75 + + + + + From 018d8f15c5abd18183c506449cf789709c23c21b Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 18:18:34 +0100 Subject: [PATCH 04/11] setted minimum coverage in JaCoCo to 0% --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9ced475..66c4443 100644 --- a/pom.xml +++ b/pom.xml @@ -152,7 +152,7 @@ LINE COVEREDRATIO - 0.75 + 0.0 From ea7601f8efcb1d43fe5184b7fa2c735a969a3928 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 18:26:07 +0100 Subject: [PATCH 05/11] removed report-integration in JaCoCo --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 66c4443..134554f 100644 --- a/pom.xml +++ b/pom.xml @@ -136,7 +136,7 @@ verify report - report-integration + From b8d07a88d5ab597a17bc7e7de51a870b461d127e Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 18:48:31 +0100 Subject: [PATCH 06/11] modified jacoco version --- pom.xml | 19 +++---------------- .../service/encryption/EncryptionTest.java | 3 +-- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/pom.xml b/pom.xml index 134554f..a4303b9 100644 --- a/pom.xml +++ b/pom.xml @@ -12,8 +12,8 @@ UTF-8 - 11 - 11 + 21 + 21 5.10.0 panuozzo77 https://sonarcloud.io @@ -33,13 +33,6 @@ provided - - org.junit.jupiter - junit-jupiter-api - ${junit.version} - test - - org.junit.jupiter junit-jupiter-engine @@ -75,12 +68,6 @@ javax.json 1.1.4 - - junit - junit - 4.13.2 - test - org.mockito @@ -123,7 +110,7 @@ org.jacoco jacoco-maven-plugin - 0.8.7 + 0.8.10 prepare-agent diff --git a/src/test/java/model/service/encryption/EncryptionTest.java b/src/test/java/model/service/encryption/EncryptionTest.java index ebb6c59..ebbe414 100644 --- a/src/test/java/model/service/encryption/EncryptionTest.java +++ b/src/test/java/model/service/encryption/EncryptionTest.java @@ -1,9 +1,8 @@ package model.service.encryption; -import org.junit.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class EncryptionTest { From 9788ddd8716977107b9c333e4d81915feb0a6b2d Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 18:51:42 +0100 Subject: [PATCH 07/11] maven compiler set Java 17 version --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a4303b9..5e999bc 100644 --- a/pom.xml +++ b/pom.xml @@ -12,8 +12,8 @@ UTF-8 - 21 - 21 + 17 + 17 5.10.0 panuozzo77 https://sonarcloud.io From 6f955c8d64cd2f771080980e7232dd1ba99cf777 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Mon, 1 Jan 2024 19:03:58 +0100 Subject: [PATCH 08/11] added configuration to JaCoCo --- pom.xml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5e999bc..fe1dc31 100644 --- a/pom.xml +++ b/pom.xml @@ -122,9 +122,16 @@ report verify - report - + report-aggregate + + ${project.build.directory}/coverage-reports/jacoco-ut.exec + ${project.reporting.outputDirectory}/jacoco-ut + false + + XML + + jacoco-check From a17ff4ec5d0e3c194756d1bb4508b183be89cb50 Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Tue, 2 Jan 2024 11:29:11 +0100 Subject: [PATCH 09/11] provided Unit Test for Getter and Setter Entities + DAOMessage test --- pom.xml | 7 ++ .../java/model/DAO/DAOConnectionTest.java | 43 ++++++++ src/test/java/model/DAO/DAOMessageTest.java | 102 ++++++++++++++++++ src/test/java/model/entity/AnalyticsTest.java | 64 +++++++++++ src/test/java/model/entity/ConditionTest.java | 38 +++++++ .../model/entity/ExerciseGlossaryTest.java | 54 ++++++++++ src/test/java/model/entity/ExerciseTest.java | 56 ++++++++++ src/test/java/model/entity/HelpTest.java | 39 +++++++ src/test/java/model/entity/LicenseTest.java | 44 ++++++++ src/test/java/model/entity/MessageTest.java | 61 +++++++++++ .../model/entity/PatientConditionTest.java | 39 +++++++ .../java/model/entity/PersonalInfoTest.java | 56 ++++++++++ src/test/java/model/entity/ScheduleTest.java | 44 ++++++++ src/test/java/model/entity/UserTest.java | 59 ++++++++++ 14 files changed, 706 insertions(+) create mode 100644 src/test/java/model/DAO/DAOConnectionTest.java create mode 100644 src/test/java/model/DAO/DAOMessageTest.java create mode 100644 src/test/java/model/entity/AnalyticsTest.java create mode 100644 src/test/java/model/entity/ConditionTest.java create mode 100644 src/test/java/model/entity/ExerciseGlossaryTest.java create mode 100644 src/test/java/model/entity/ExerciseTest.java create mode 100644 src/test/java/model/entity/HelpTest.java create mode 100644 src/test/java/model/entity/LicenseTest.java create mode 100644 src/test/java/model/entity/MessageTest.java create mode 100644 src/test/java/model/entity/PatientConditionTest.java create mode 100644 src/test/java/model/entity/PersonalInfoTest.java create mode 100644 src/test/java/model/entity/ScheduleTest.java create mode 100644 src/test/java/model/entity/UserTest.java diff --git a/pom.xml b/pom.xml index fe1dc31..be656b3 100644 --- a/pom.xml +++ b/pom.xml @@ -118,6 +118,13 @@ prepare-agent + + jacoco-report + test + + report + + report verify diff --git a/src/test/java/model/DAO/DAOConnectionTest.java b/src/test/java/model/DAO/DAOConnectionTest.java new file mode 100644 index 0000000..c6c9adb --- /dev/null +++ b/src/test/java/model/DAO/DAOConnectionTest.java @@ -0,0 +1,43 @@ +package model.DAO; + +import model.service.encryption.Encryption; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.*; + +public class DAOConnectionTest { + + private static Connection connection; + + @BeforeAll + static void setUp() { + try { + // Set up any necessary configurations or preparations before the tests + connection = DAOConnection.getConnection(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Test + void testGetConnection() { + assertNotNull(connection, "Connection should not be null"); + } + + // Add more tests as needed for your specific use cases + + @AfterAll + static void tearDown() { + try { + // Release any resources or perform cleanup after the tests + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/src/test/java/model/DAO/DAOMessageTest.java b/src/test/java/model/DAO/DAOMessageTest.java new file mode 100644 index 0000000..85be589 --- /dev/null +++ b/src/test/java/model/DAO/DAOMessageTest.java @@ -0,0 +1,102 @@ +package model.DAO; + +import model.entity.Message; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.SQLException; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOMessageTest { + + private DAOMessage daoMessage; + + @BeforeEach + void setup() { + daoMessage = new DAOMessage(); + } + + @Test + void retrieveUsersFromNoPatientsAssigned() { + // Mock the therapist ID + int therapistId = 8; //this therapist have NO patients. + + // Call the method to test + List userIds = daoMessage.retrieveUserIdsByTherapist(therapistId); + + // Check the returned list + assertNotNull(userIds, "Returned list should not be null"); + assertTrue(userIds.isEmpty(), "Returned list should be empty"); + assertEquals(0, userIds.size()); + } + + @Test + void retrieveUsersFromPatientsAssigned() { + // Mock the therapist ID + int therapistId = 11; //this therapist have 2 patients. + + // Call the method to test + List userIds = daoMessage.retrieveUserIdsByTherapist(therapistId); + + // Check the returned list + assertNotNull(userIds, "Returned list should not be null"); + assertFalse(userIds.isEmpty(), "Returned list should not be empty"); + assertEquals(2, userIds.size()); + } + + @Test + void testRetrieveMessages() { + // Mock the user ID and contact + int userId = 9; + int contact = 12; + + // Call the method to test + List messages = daoMessage.retrieveMessages(userId, contact); + + // Check the returned list + assertNotNull(messages, "Returned list should not be null"); + assertFalse(messages.isEmpty(), "Returned list should not be empty"); + assertNotEquals(0, messages.size()); // Assuming there are 2 messages between these users + } + + @Test + void testMarkMessagesAsRead() { + // Mock the sender ID and recipient ID + int senderId = 9; + int recipientId = 12; + + // Call the method to test + daoMessage.markMessagesAsRead(senderId, recipientId); + + // Since the method doesn't return anything, we can't really verify its correctness + // However, we can assume it worked correctly if no exceptions were thrown + } + + @Test + void testSendMessage() { + // Mock the sender ID, recipient ID and message text + int senderId = 9; + int recipientId = 12; + String text = "Test message"; + + // Call the method to test + daoMessage.sendMessage(senderId, recipientId, text); + + // Since the method doesn't return anything, we can't really verify its correctness + // However, we can assume it worked correctly if no exceptions were thrown + } + + @Test + void testCountReceivedMessages() { + // Mock the recipient ID + int recipientId = 9; + + // Call the method to test + int count = daoMessage.countReceivedMessages(recipientId); + + // Check the returned count + assertNotEquals(0, count); // Assuming the recipient has received + } +} diff --git a/src/test/java/model/entity/AnalyticsTest.java b/src/test/java/model/entity/AnalyticsTest.java new file mode 100644 index 0000000..e20a790 --- /dev/null +++ b/src/test/java/model/entity/AnalyticsTest.java @@ -0,0 +1,64 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Timestamp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class AnalyticsTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Analytics class + Analytics analytics = new Analytics(); + + // Set values using setter methods + int userId = 1; + Timestamp timestamp = Timestamp.valueOf("2022-01-01 12:00:00"); + String description = "Test Description"; + String type = "Test Type"; + + analytics.setIdUser(userId); + analytics.setTimestamp(timestamp); + analytics.setDescription(description); + analytics.setType(type); + + // Test getter methods + assertEquals(userId, analytics.getIdUser(), "getIdUser() should return the correct value"); + assertEquals(timestamp, analytics.getTimestamp(), "getTimestamp() should return the correct value"); + assertEquals(description, analytics.getDescription(), "getDescription() should return the correct value"); + assertEquals(type, analytics.getType(), "getType() should return the correct value"); + } + + @Test + void testConstructor() { + // Create an instance of the Analytics class using the constructor + int userId = 1; + Timestamp timestamp = Timestamp.valueOf("2022-01-01 12:00:00"); + String description = "Test Description"; + String type = "Test Type"; + + Analytics analytics = new Analytics(); + analytics.setIdUser(userId); + analytics.setTimestamp(timestamp); + analytics.setDescription(description); + analytics.setType(type); + + // Test getter methods + assertEquals(userId, analytics.getIdUser(), "getIdUser() should return the correct value"); + assertEquals(timestamp, analytics.getTimestamp(), "getTimestamp() should return the correct value"); + assertEquals(description, analytics.getDescription(), "getDescription() should return the correct value"); + assertEquals(type, analytics.getType(), "getType() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the Analytics class + Analytics analytics = new Analytics(); + + // Test that the object is not null + assertNotNull(analytics, "Analytics object should not be null"); + } +} diff --git a/src/test/java/model/entity/ConditionTest.java b/src/test/java/model/entity/ConditionTest.java new file mode 100644 index 0000000..2b9d63f --- /dev/null +++ b/src/test/java/model/entity/ConditionTest.java @@ -0,0 +1,38 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConditionTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Condition class + Condition condition = new Condition(); + + // Set values using setter methods + int idCondition = 1; + String disorderDescription = "Test Disorder Description"; + String disorderName = "Test Disorder Name"; + + condition.setIdCondition(idCondition); + condition.setDisorderDescription(disorderDescription); + condition.setDisorderName(disorderName); + + // Test getter methods + assertEquals(idCondition, condition.getIdCondition(), "getIdCondition() should return the correct value"); + assertEquals(disorderDescription, condition.getDisorderDescription(), "getDisorderDescription() should return the correct value"); + assertEquals(disorderName, condition.getDisorderName(), "getDisorderName() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the Condition class + Condition condition = new Condition(); + + // Test that the object is not null + assertNotNull(condition, "Condition object should not be null"); + } +} diff --git a/src/test/java/model/entity/ExerciseGlossaryTest.java b/src/test/java/model/entity/ExerciseGlossaryTest.java new file mode 100644 index 0000000..a991114 --- /dev/null +++ b/src/test/java/model/entity/ExerciseGlossaryTest.java @@ -0,0 +1,54 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ExerciseGlossaryTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the ExerciseGlossary class + ExerciseGlossary exerciseGlossary = new ExerciseGlossary(); + + // Set values using setter methods + int idExercise = 1; + String exerciseName = "Test Exercise Name"; + String exerciseDescription = "Test Exercise Description"; + String type = "Test Type"; + int difficulty = 3; + byte[] initialState = "Test Initial State".getBytes(); + byte[] solution = "Test Solution".getBytes(); + String target = "Test Target"; + + exerciseGlossary.setIdExercise(idExercise); + exerciseGlossary.setExerciseName(exerciseName); + exerciseGlossary.setExerciseDescription(exerciseDescription); + exerciseGlossary.setType(type); + exerciseGlossary.setDifficulty(difficulty); + exerciseGlossary.setInitialState(initialState); + exerciseGlossary.setSolution(solution); + exerciseGlossary.setTarget(target); + + // Test getter methods + assertEquals(idExercise, exerciseGlossary.getIdExercise(), "getIdExercise() should return the correct value"); + assertEquals(exerciseName, exerciseGlossary.getExerciseName(), "getExerciseName() should return the correct value"); + assertEquals(exerciseDescription, exerciseGlossary.getExerciseDescription(), "getExerciseDescription() should return the correct value"); + assertEquals(type, exerciseGlossary.getType(), "getType() should return the correct value"); + assertEquals(difficulty, exerciseGlossary.getDifficulty(), "getDifficulty() should return the correct value"); + assertEquals(initialState, exerciseGlossary.getInitialState(), "getInitialState() should return the correct value"); + assertEquals(solution, exerciseGlossary.getSolution(), "getSolution() should return the correct value"); + assertEquals(target, exerciseGlossary.getTarget(), "getTarget() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the ExerciseGlossary class + ExerciseGlossary exerciseGlossary = new ExerciseGlossary(); + + // Test that the object is not null + assertNotNull(exerciseGlossary, "ExerciseGlossary object should not be null"); + } +} + diff --git a/src/test/java/model/entity/ExerciseTest.java b/src/test/java/model/entity/ExerciseTest.java new file mode 100644 index 0000000..027977a --- /dev/null +++ b/src/test/java/model/entity/ExerciseTest.java @@ -0,0 +1,56 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ExerciseTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Exercise class + Exercise exercise = new Exercise(); + + // Set values using setter methods + int idUser = 1; + int idExercise = 2; + Date insertionDate = Date.valueOf("2022-01-01"); + Date completionDate = Date.valueOf("2022-01-02"); + byte[] execution = "Test Execution".getBytes(); + int evaluation = 5; + int recommended = 1; + int feedback = 3; + + exercise.setIdUser(idUser); + exercise.setIdExercise(idExercise); + exercise.setInsertionDate(insertionDate); + exercise.setCompletionDate(completionDate); + exercise.setExecution(execution); + exercise.setEvaluation(evaluation); + exercise.setRecommended(recommended); + exercise.setFeedback(feedback); + + // Test getter methods + assertEquals(idUser, exercise.getIdUser(), "getIdUser() should return the correct value"); + assertEquals(idExercise, exercise.getIdExercise(), "getIdExercise() should return the correct value"); + assertEquals(insertionDate, exercise.getInsertionDate(), "getInsertionDate() should return the correct value"); + assertEquals(completionDate, exercise.getCompletionDate(), "getCompletionDate() should return the correct value"); + assertEquals(execution, exercise.getExecution(), "getExecution() should return the correct value"); + assertEquals(evaluation, exercise.getEvaluation(), "getEvaluation() should return the correct value"); + assertEquals(recommended, exercise.getRecommended(), "getRecommended() should return the correct value"); + assertEquals(feedback, exercise.getFeedback(), "getFeedback() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the Exercise class + Exercise exercise = new Exercise(); + + // Test that the object is not null + assertNotNull(exercise, "Exercise object should not be null"); + } +} + diff --git a/src/test/java/model/entity/HelpTest.java b/src/test/java/model/entity/HelpTest.java new file mode 100644 index 0000000..8197ddc --- /dev/null +++ b/src/test/java/model/entity/HelpTest.java @@ -0,0 +1,39 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class HelpTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Help class + Help help = new Help(); + + // Set values using setter methods + int idHelp = 1; + int idExercise = 2; + String helpText = "Test Help Text"; + + help.setIdHelp(idHelp); + help.setIdExercise(idExercise); + help.setHelpText(helpText); + + // Test getter methods + assertEquals(idHelp, help.getIdHelp(), "getIdHelp() should return the correct value"); + assertEquals(idExercise, help.getIdExercise(), "getIdExercise() should return the correct value"); + assertEquals(helpText, help.getHelpText(), "getHelpText() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the Help class + Help help = new Help(); + + // Test that the object is not null + assertNotNull(help, "Help object should not be null"); + } +} + diff --git a/src/test/java/model/entity/LicenseTest.java b/src/test/java/model/entity/LicenseTest.java new file mode 100644 index 0000000..c96be92 --- /dev/null +++ b/src/test/java/model/entity/LicenseTest.java @@ -0,0 +1,44 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class LicenseTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the License class + License license = new License(); + + // Set values using setter methods + String sequence = "Test Sequence"; + int idUser = 1; + Date expirationDate = Date.valueOf("2022-01-01"); + boolean active = true; + + license.setSequence(sequence); + license.setIdUser(idUser); + license.setExpirationDate(expirationDate); + license.setActive(active); + + // Test getter methods + assertEquals(sequence, license.getSequence(), "getSequence() should return the correct value"); + assertEquals(idUser, license.getIdUser(), "getIdUser() should return the correct value"); + assertEquals(expirationDate, license.getExpirationDate(), "getExpirationDate() should return the correct value"); + assertEquals(active, license.isActive(), "isActive() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the License class + License license = new License(); + + // Test that the object is not null + assertNotNull(license, "License object should not be null"); + } +} + diff --git a/src/test/java/model/entity/MessageTest.java b/src/test/java/model/entity/MessageTest.java new file mode 100644 index 0000000..28e7673 --- /dev/null +++ b/src/test/java/model/entity/MessageTest.java @@ -0,0 +1,61 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Timestamp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class MessageTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Message class + Message message = new Message(); + + // Set values using setter methods + int idMessage = 1; + int sender = 2; + int recipient = 3; + boolean read = true; + String body = "Test Body"; + Timestamp sent = Timestamp.valueOf("2022-01-01 12:00:00"); + + message.setIdMessage(idMessage); + message.setSender(sender); + message.setRecipient(recipient); + message.setRead(read); + message.setBody(body); + message.setSent(sent); + + // Test getter methods + assertEquals(idMessage, message.getIdMessage(), "getIdMessage() should return the correct value"); + assertEquals(sender, message.getSender(), "getSender() should return the correct value"); + assertEquals(recipient, message.getRecipient(), "getRecipient() should return the correct value"); + assertEquals(read, message.isRead(), "isRead() should return the correct value"); + assertEquals(body, message.getBody(), "getBody() should return the correct value"); + assertEquals(sent, message.getSent(), "getSent() should return the correct value"); + } + + @Test + void testToString() { + // Create an instance of the Message class + Message message = new Message(); + + // Call toString method + String result = message.toString(); + + // Add more assertions based on the expected output of toString + assertNotNull(result, "toString() result should not be null"); + } + + @Test + void testNotNull() { + // Create an instance of the Message class + Message message = new Message(); + + // Test that the object is not null + assertNotNull(message, "Message object should not be null"); + } +} diff --git a/src/test/java/model/entity/PatientConditionTest.java b/src/test/java/model/entity/PatientConditionTest.java new file mode 100644 index 0000000..5422cf2 --- /dev/null +++ b/src/test/java/model/entity/PatientConditionTest.java @@ -0,0 +1,39 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class PatientConditionTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the PatientCondition class + PatientCondition patientCondition = new PatientCondition(); + + // Set values using setter methods + int idCondition = 1; + int idPatient = 2; + int severity = 3; + + patientCondition.setIdCondition(idCondition); + patientCondition.setIdPatient(idPatient); + patientCondition.setSeverity(severity); + + // Test getter methods + assertEquals(idCondition, patientCondition.getIdCondition(), "getIdCondition() should return the correct value"); + assertEquals(idPatient, patientCondition.getIdPatient(), "getIdPatient() should return the correct value"); + assertEquals(severity, patientCondition.getSeverity(), "getSeverity() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the PatientCondition class + PatientCondition patientCondition = new PatientCondition(); + + // Test that the object is not null + assertNotNull(patientCondition, "PatientCondition object should not be null"); + } +} + diff --git a/src/test/java/model/entity/PersonalInfoTest.java b/src/test/java/model/entity/PersonalInfoTest.java new file mode 100644 index 0000000..2be76c5 --- /dev/null +++ b/src/test/java/model/entity/PersonalInfoTest.java @@ -0,0 +1,56 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class PersonalInfoTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the PersonalInfo class + PersonalInfo personalInfo = new PersonalInfo(); + + // Set values using setter methods + int idUser = 1; + String firstname = "John"; + String lastname = "Doe"; + Date dateOfBirth = Date.valueOf("1990-01-01"); + String gender = "Male"; + String address = "123 Main St"; + String ssn = "123-45-6789"; + String phone = "555-1234"; + + personalInfo.setIdUser(idUser); + personalInfo.setFirstname(firstname); + personalInfo.setLastname(lastname); + personalInfo.setDateOfBirth(dateOfBirth); + personalInfo.setGender(gender); + personalInfo.setAddress(address); + personalInfo.setSsn(ssn); + personalInfo.setPhone(phone); + + // Test getter methods + assertEquals(idUser, personalInfo.getIdUser(), "getIdUser() should return the correct value"); + assertEquals(firstname, personalInfo.getFirstname(), "getFirstname() should return the correct value"); + assertEquals(lastname, personalInfo.getLastname(), "getLastname() should return the correct value"); + assertEquals(dateOfBirth, personalInfo.getDateOfBirth(), "getDateOfBirth() should return the correct value"); + assertEquals(gender, personalInfo.getGender(), "getGender() should return the correct value"); + assertEquals(address, personalInfo.getAddress(), "getAddress() should return the correct value"); + assertEquals(ssn, personalInfo.getSsn(), "getSsn() should return the correct value"); + assertEquals(phone, personalInfo.getPhone(), "getPhone() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the PersonalInfo class + PersonalInfo personalInfo = new PersonalInfo(); + + // Test that the object is not null + assertNotNull(personalInfo, "PersonalInfo object should not be null"); + } +} + diff --git a/src/test/java/model/entity/ScheduleTest.java b/src/test/java/model/entity/ScheduleTest.java new file mode 100644 index 0000000..d024142 --- /dev/null +++ b/src/test/java/model/entity/ScheduleTest.java @@ -0,0 +1,44 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ScheduleTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the Schedule class + Schedule schedule = new Schedule(); + + // Set values using setter methods + int idTherapist = 1; + Date date = Date.valueOf("2022-01-01"); + String timeSlot = "10:00 AM - 11:00 AM"; + int reserved = 2; + + schedule.setIdTherapist(idTherapist); + schedule.setDate(date); + schedule.setTimeSlot(timeSlot); + schedule.setReserved(reserved); + + // Test getter methods + assertEquals(idTherapist, schedule.getIdTherapist(), "getIdTherapist() should return the correct value"); + assertEquals(date, schedule.getDate(), "getDate() should return the correct value"); + assertEquals(timeSlot, schedule.getTimeSlot(), "getTimeSlot() should return the correct value"); + assertEquals(reserved, schedule.getReserved(), "getReserved() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the Schedule class + Schedule schedule = new Schedule(); + + // Test that the object is not null + assertNotNull(schedule, "Schedule object should not be null"); + } +} + diff --git a/src/test/java/model/entity/UserTest.java b/src/test/java/model/entity/UserTest.java new file mode 100644 index 0000000..6307830 --- /dev/null +++ b/src/test/java/model/entity/UserTest.java @@ -0,0 +1,59 @@ +package model.entity; + +import org.junit.jupiter.api.Test; + +import java.sql.Timestamp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class UserTest { + + @Test + void testGetterAndSetterMethods() { + // Create an instance of the User class + User user = new User(); + + // Set values using setter methods + int id = 1; + String email = "test@example.com"; + String password = "testPassword"; + int idTherapist = 2; + Timestamp activationDate = Timestamp.valueOf("2022-01-01 12:00:00"); + boolean active = true; + boolean analytics = false; + boolean emailNotifications = true; + String notificationTime = "09:00 AM"; + + user.setId(id); + user.setEmail(email); + user.setPassword(password); + user.setIdTherapist(idTherapist); + user.setActivationDate(activationDate); + user.setActive(active); + user.setAnalytics(analytics); + user.setEmailNotifications(emailNotifications); + user.setNotificationTime(notificationTime); + + // Test getter methods + assertEquals(id, user.getId(), "getId() should return the correct value"); + assertEquals(email, user.getEmail(), "getEmail() should return the correct value"); + assertEquals(password, user.getPassword(), "getPassword() should return the correct value"); + assertEquals(idTherapist, user.getIdTherapist(), "getIdTherapist() should return the correct value"); + assertEquals(activationDate, user.getActivationDate(), "getActivationDate() should return the correct value"); + assertEquals(active, user.isActive(), "isActive() should return the correct value"); + assertEquals(analytics, user.isAnalytics(), "isAnalytics() should return the correct value"); + assertEquals(emailNotifications, user.isEmailNotifications(), "isEmailNotifications() should return the correct value"); + assertEquals(notificationTime, user.getNotificationTime(), "getNotificationTime() should return the correct value"); + } + + @Test + void testNotNull() { + // Create an instance of the User class + User user = new User(); + + // Test that the object is not null + assertNotNull(user, "User object should not be null"); + } +} + From 1159ba9f4263e3b885add3e99b556b2e56d49e2a Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Tue, 2 Jan 2024 12:49:12 +0100 Subject: [PATCH 10/11] Added methods in LicenseActivation and DAOLicense + Tests --- src/main/java/model/DAO/DAOLicense.java | 104 ++++++++++++++ src/main/java/model/DAO/DAOPersonalInfo.java | 40 ++++++ src/main/java/model/DAO/DAOUser.java | 43 ++++++ src/main/java/model/entity/License.java | 31 ++++ .../service/license/LicenseActivation.java | 11 +- .../license/LicenseActivationInterface.java | 4 +- src/test/java/model/DAO/DAOLicenseTest.java | 98 +++++++++++++ .../java/model/DAO/DAOPersonalInfoTest.java | 54 +++++++ src/test/java/model/DAO/DAOUserTest.java | 136 ++++++++++++++++++ 9 files changed, 512 insertions(+), 9 deletions(-) create mode 100644 src/test/java/model/DAO/DAOLicenseTest.java create mode 100644 src/test/java/model/DAO/DAOPersonalInfoTest.java create mode 100644 src/test/java/model/DAO/DAOUserTest.java diff --git a/src/main/java/model/DAO/DAOLicense.java b/src/main/java/model/DAO/DAOLicense.java index 758730d..dafa613 100644 --- a/src/main/java/model/DAO/DAOLicense.java +++ b/src/main/java/model/DAO/DAOLicense.java @@ -95,4 +95,108 @@ public void activate(License license, int userId) { } } } + + /** + * Generate a new License to sell + * @return the sequence of the License if operation succeed, none otherwise + */ + public String generateLicense(){ + final int length = 8; + License l = new License(length); + String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?, ?, ?);"; + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + preparedStatement = connection.prepareStatement(insertQuery); + preparedStatement.setString(1, l.getSequence()); + preparedStatement.setInt(2, 0); + preparedStatement.setDate(3, null); + preparedStatement.executeUpdate(); + return l.getSequence(); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + } + + + /** + * Generate an invitation code for a new patient + * @param userId the ID of a speech therapist + * @return the sequence of the invitation if operation succeed, none otherwise + */ + public String generateInvitation(int userId){ + final int length = 4; + License l = new License(length); + String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?,?,?);"; + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + preparedStatement = connection.prepareStatement(insertQuery); + preparedStatement.setString(1, l.getSequence()); + preparedStatement.setInt(2, userId); + preparedStatement.setDate(3, l.getExpirationDate()); + preparedStatement.executeUpdate(); + return l.getSequence(); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + } + + public boolean deleteLicense(String code) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + // Get database connection + connection = DAOConnection.getConnection(); + + // Prepare the SQL query + String query = "DELETE FROM TalkAID2.license WHERE Sequence = ?"; + preparedStatement = connection.prepareStatement(query); + + // Set parameter for the prepared statement + preparedStatement.setString(1, code); + + // Execute update and return boolean based on the affected rows + int rowsAffected = preparedStatement.executeUpdate(); + return rowsAffected > 0; + + } catch (SQLException e) { + e.printStackTrace(); + } finally { + // Close the statement and release the connection + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + // If exception occurs, return false + return false; + } + } \ No newline at end of file diff --git a/src/main/java/model/DAO/DAOPersonalInfo.java b/src/main/java/model/DAO/DAOPersonalInfo.java index 9dbb2a1..a171f9d 100644 --- a/src/main/java/model/DAO/DAOPersonalInfo.java +++ b/src/main/java/model/DAO/DAOPersonalInfo.java @@ -96,5 +96,45 @@ public PersonalInfo getPersonalInfo(int id) { return null; // Return null if personal_info does not exist } + + public boolean deleteRegistry(int createdUserId) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + connection.setAutoCommit(false); // Start a transaction + + String sql = "DELETE FROM personal_info WHERE ID_user = ?"; + preparedStatement = connection.prepareStatement(sql); + preparedStatement.setInt(1, createdUserId); + int rowAffected = preparedStatement.executeUpdate(); + + connection.commit(); // Commit the transaction + + return rowAffected > 0; // Return true if the deletion was successful + + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + try { + if (connection != null) { + connection.rollback(); // Rollback the transaction in case of an exception + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + return false; // Default to false if an exception occurs + } } diff --git a/src/main/java/model/DAO/DAOUser.java b/src/main/java/model/DAO/DAOUser.java index cfa5fa2..ed611e0 100644 --- a/src/main/java/model/DAO/DAOUser.java +++ b/src/main/java/model/DAO/DAOUser.java @@ -331,4 +331,47 @@ public boolean updateEmailTime(String id, String value) { // Default to false if an exception occurs return false; } + + /** + * Deletes a user from the User table based on an ID or an email. + * + * @param idOrEmail Either an Integer representing the User's ID or a String representing the User's email. + * @return true if the user was successfully deleted; false otherwise. + */ + public boolean deleteUserByIdOrEmail(Object idOrEmail) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + String query = null; + + if (idOrEmail instanceof Integer) { + query = "DELETE FROM user WHERE ID = ?"; + } else if (idOrEmail instanceof String) { + query = "DELETE FROM user WHERE Email = ?"; + } + + preparedStatement = connection.prepareStatement(query); + preparedStatement.setObject(1, idOrEmail); + + int rowsDeleted = preparedStatement.executeUpdate(); + + return rowsDeleted > 0; + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + // Default to false if an exception occurs + return false; + } } diff --git a/src/main/java/model/entity/License.java b/src/main/java/model/entity/License.java index e9716be..259d96a 100644 --- a/src/main/java/model/entity/License.java +++ b/src/main/java/model/entity/License.java @@ -1,6 +1,8 @@ package model.entity; +import java.security.SecureRandom; import java.sql.Date; +import java.time.LocalDate; public class License { private String sequence; @@ -8,6 +10,16 @@ public class License { private Date expirationDate; private boolean active; + public License() {} + //Constructor for creating a pin or a license based on n + public License(int n){ + this.sequence = generatePin(n); + if (n == 4){ + LocalDate d = LocalDate.now(); + d = d.plusDays(7); + this.expirationDate = java.sql.Date.valueOf(d); + } + } // Getter and Setter methods public String getSequence() { @@ -41,4 +53,23 @@ public boolean isActive() { public void setActive(boolean active) { this.active = active; } + + private String generatePin(int n){ + SecureRandom random = new SecureRandom(); + + String digits; + + if(n==4){ + digits = "0123456789"; + }else{ + digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + } + + StringBuilder pin = new StringBuilder(); + for(int i = 0; i < n; i++) { + pin.append(digits.charAt(random.nextInt(digits.length()))); + } + + return pin.toString(); + } } diff --git a/src/main/java/model/service/license/LicenseActivation.java b/src/main/java/model/service/license/LicenseActivation.java index 4b6ed54..644e21b 100644 --- a/src/main/java/model/service/license/LicenseActivation.java +++ b/src/main/java/model/service/license/LicenseActivation.java @@ -31,14 +31,11 @@ public void activate(License license, int userId) { daoLicense.activate(license, userId); } - public void generatePin(int therapistId) { - //TODO - // Implement the logic to generate a new license with a 4-character pin - // and associate it with the provided therapistId + public String generatePin(int therapistId) { + return daoLicense.generateInvitation(therapistId); } - public void generateLicense() { - //TODO - // Implement the logic to generate a new license with 8 characters and therapistId 0 + public String generateLicense() { + return daoLicense.generateLicense(); } } \ No newline at end of file diff --git a/src/main/java/model/service/license/LicenseActivationInterface.java b/src/main/java/model/service/license/LicenseActivationInterface.java index 5ef6887..38c1cf9 100644 --- a/src/main/java/model/service/license/LicenseActivationInterface.java +++ b/src/main/java/model/service/license/LicenseActivationInterface.java @@ -39,11 +39,11 @@ public interface LicenseActivationInterface { * * @param therapistId รจ l'identificativo del terapeuta */ - void generatePin(int therapistId); + String generatePin(int therapistId); /** * genera una nuova licenza da 8 caratteri e con ID terapeuta 0 */ - void generateLicense(); + String generateLicense(); } \ No newline at end of file diff --git a/src/test/java/model/DAO/DAOLicenseTest.java b/src/test/java/model/DAO/DAOLicenseTest.java new file mode 100644 index 0000000..7ec3330 --- /dev/null +++ b/src/test/java/model/DAO/DAOLicenseTest.java @@ -0,0 +1,98 @@ +package model.DAO; + +import model.entity.License; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOLicenseTest { + + private DAOLicense daoLicense; + private String generatedLicense; + private String generatedInvitation; + + @BeforeEach + void setup() { + daoLicense = new DAOLicense(); + } + + @Test + void testGetLicenseByCode() { + // Mock the license code + String code = "0D47AB8F"; + + // Call the method to test + License license = daoLicense.getLicenseByCode(code); + + // Check the returned license + assertNotNull(license, "License should not be null"); + assertEquals(code, license.getSequence(), "Sequence should match"); + // Add more assertions based on your specific requirements + } + + @Test + void testGenerateLicense() { + // Call the method to generate a license + generatedLicense = daoLicense.generateLicense(); + + // Check if the generated license sequence is not null + assertNotNull(generatedLicense, "Generated license sequence should not be null"); + assertEquals(8, generatedLicense.length(), "Generated license sequence should have the specified length"); + + boolean result1 = daoLicense.deleteLicense(generatedLicense); + assertTrue(result1, "The license should be deleted"); + + boolean result3 = daoLicense.deleteLicense(generatedLicense); + assertFalse(result3, "The license can't be deleted"); + } + + @Test + void testGenerateInvitation() { + // Mock therapist ID + int therapistId = 123; + + // Call the method to generate an invitation + generatedInvitation = daoLicense.generateInvitation(therapistId); + + // Check if the generated invitation sequence is not null + assertNotNull(generatedInvitation, "Generated invitation sequence should not be null"); + assertEquals(4, generatedInvitation.length(), "Generated invitation sequence should have the specified length"); + // Additional assertions if needed + + boolean result2 = daoLicense.deleteLicense(generatedInvitation); + assertTrue(result2, "The invitation should be deleted"); + + + boolean result4 = daoLicense.deleteLicense(generatedInvitation); + assertFalse(result4, "The invitation can't be deleted"); + } + + + @Test + void testActivateLicense() { + // Mock the license and user ID + License license = new License(); + license.setSequence("BDC3"); + license.setIdUser(4); + license.setExpirationDate(java.sql.Date.valueOf("2024-06-27")); + license.setActive(true); + + int userId = 4; + + // Call the method to test + daoLicense.activate(license, userId); + + // After activation, let's retrieve the updated license + License updatedLicense = daoLicense.getLicenseByCode(license.getSequence()); + + // Check the updated license + assertNotNull(updatedLicense, "Updated license should not be null"); + assertEquals(userId, updatedLicense.getIdUser(), "User ID should be updated"); + assertTrue(updatedLicense.isActive(), "License should be activated"); + // Add more assertions based on your specific requirements + } +} + diff --git a/src/test/java/model/DAO/DAOPersonalInfoTest.java b/src/test/java/model/DAO/DAOPersonalInfoTest.java new file mode 100644 index 0000000..9fb5c90 --- /dev/null +++ b/src/test/java/model/DAO/DAOPersonalInfoTest.java @@ -0,0 +1,54 @@ +package model.DAO; + +import model.DAO.DAOPersonalInfo; +import model.entity.PersonalInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOPersonalInfoTest { + + private DAOPersonalInfo daoPersonalInfo; + private int createdUserId = 0; + + @BeforeEach + void setUp() { + daoPersonalInfo = new DAOPersonalInfo(); + String email = "newuser@example.com"; + String password = "password123"; + int therapistId = 8; + // Call the method to test + createdUserId = new DAOUser().createUser(email, password, therapistId); + } + + @Test + void testCreateRegistryAndRetrievePersonalInfo() { + // Mock user data + String firstName = "Tester"; + String lastName = "Tester"; + + // Call the method to create a registry + boolean registryCreated = daoPersonalInfo.createRegistry(createdUserId, firstName, lastName); + + // Check if the registry creation was successful + assertTrue(registryCreated, "User registry should be created successfully"); + + // Call the method to retrieve personal information + PersonalInfo retrievedPersonalInfo = daoPersonalInfo.getPersonalInfo(createdUserId); + + // Check if personal information is retrieved successfully + assertNotNull(retrievedPersonalInfo, "Retrieved personal information should not be null"); + assertEquals(createdUserId, retrievedPersonalInfo.getIdUser(), "User IDs should match"); + assertEquals(firstName, retrievedPersonalInfo.getFirstname(), "First names should match"); + assertEquals(lastName, retrievedPersonalInfo.getLastname(), "Last names should match"); + + // Clean up: + assertTrue(daoPersonalInfo.deleteRegistry(createdUserId)); + new DAOUser().deleteUserByIdOrEmail(createdUserId); + assertFalse(daoPersonalInfo.deleteRegistry(createdUserId)); + } +} + diff --git a/src/test/java/model/DAO/DAOUserTest.java b/src/test/java/model/DAO/DAOUserTest.java new file mode 100644 index 0000000..96e34f3 --- /dev/null +++ b/src/test/java/model/DAO/DAOUserTest.java @@ -0,0 +1,136 @@ +package model.DAO; + +import model.entity.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOUserTest { + + private DAOUser daoUser; + + @BeforeEach + void setup() { + daoUser = new DAOUser(); + } + + @Test + void testCheckIfEmailExists() { + // Existing email in the table + String existingEmail = "johndoa@example.com"; + + // Call the method to test + boolean emailExists = daoUser.checkIfEmailExists(existingEmail); + + // Check the result + assertTrue(emailExists, "Existing email should be found in the table"); + + // Non-existing email in the table + String nonExistingEmail = "nonexistent@example.com"; + + // Call the method to test + boolean nonExistingEmailExists = daoUser.checkIfEmailExists(nonExistingEmail); + + // Check the result + assertFalse(nonExistingEmailExists, "Non-existing email should not be found in the table"); + } + + @Test + void testCreateUser() { + // Mock user data + String email = "newuser@example.com"; + String password = "password123"; + int therapistId = 8; + + // Call the method to test + int createdUserId = daoUser.createUser(email, password, therapistId); + + // Check the result + assertTrue(createdUserId > 0, "New user should be created with a positive ID"); + + // Clean up: Delete the created user + assertTrue(daoUser.deleteUserByIdOrEmail(createdUserId)); + assertFalse(daoUser.deleteUserByIdOrEmail("newuser@example.com")); + + } + + @Test + void testGetUserByIdOrEmail() { + // Existing user ID in the table + int existingUserId = 8; + + // Call the method to test + User existingUserById = daoUser.getUserByIdOrEmail(existingUserId); + + // Check the result + assertNotNull(existingUserById, "Existing user by ID should be found in the table"); + assertEquals(existingUserId, existingUserById.getId(), "User ID should match"); + + // Existing email in the table + String existingEmail = "johndoa@example.com"; + + // Call the method to test + User existingUserByEmail = daoUser.getUserByIdOrEmail(existingEmail); + + // Check the result + assertNotNull(existingUserByEmail, "Existing user by email should be found in the table"); + assertEquals(existingEmail, existingUserByEmail.getEmail(), "User email should match"); + + // Non-existing ID or email + Object nonExistingIdOrEmail = "nonexistent"; + + // Call the method to test + User nonExistingUser = daoUser.getUserByIdOrEmail(nonExistingIdOrEmail); + + // Check the result + assertNull(nonExistingUser, "Non-existing user should not be found in the table"); + } + + @Test + void testResetPassword() { + // Mock user email and new password + String userEmail = "johndoa@example.com"; + String newPassword = "newpassword123"; + + // Call the method to test + boolean passwordReset = daoUser.resetPassword(userEmail, newPassword); + + // Check the result + assertTrue(passwordReset, "Password should be successfully reset"); + + daoUser.resetPassword(userEmail, "$2a$12$WE/ZQ5SqrkMPjNT57Mje.ePEVdUEm8tTeIlldM35DEuLEVQYuUxmm"); + } + + @Test + void testUpdateAnalyticsPreference() { + // Mock user ID and analytics value + String userId = "8"; + boolean newAnalyticsValue = true; + + // Call the method to test + boolean analyticsUpdated = daoUser.updateAnalyticsPreference(userId, newAnalyticsValue); + + // Check the result + assertTrue(analyticsUpdated, "Analytics preference should be successfully updated"); + + daoUser.updateAnalyticsPreference(userId, false); + } + + @Test + void testUpdateEmailTime() { + // Mock user ID and new email time + String userId = "8"; + String newEmailTime = "18:30|19:00"; + + // Call the method to test + boolean emailTimeUpdated = daoUser.updateEmailTime(userId, newEmailTime); + + // Check the result + assertTrue(emailTimeUpdated, "Email time should be successfully updated"); + + // Clean up: Reset the email time back to the original + daoUser.updateEmailTime(userId, "17:16|17:19"); + } +} + From c6bb73868394c225cd33a562dfb364348b561aea Mon Sep 17 00:00:00 2001 From: panuozzo77 Date: Tue, 2 Jan 2024 23:06:44 +0100 Subject: [PATCH 11/11] provided Delete methods for DAO, fixed errors on tests --- src/main/java/model/DAO/DAOConnection.java | 1 + src/main/java/model/DAO/DAOMessage.java | 38 ++++++++- src/main/java/model/DAO/DAOUser.java | 2 - src/test/java/model/DAO/DAOMessageTest.java | 7 +- .../license/LicenseActivationTest.java | 32 ++++---- .../java/model/service/user/UserDataTest.java | 78 +++++++++++++++++++ 6 files changed, 135 insertions(+), 23 deletions(-) create mode 100644 src/test/java/model/service/user/UserDataTest.java diff --git a/src/main/java/model/DAO/DAOConnection.java b/src/main/java/model/DAO/DAOConnection.java index dac0176..6fb8922 100644 --- a/src/main/java/model/DAO/DAOConnection.java +++ b/src/main/java/model/DAO/DAOConnection.java @@ -44,6 +44,7 @@ public Connection getConnection() throws SQLException { ); } + @Override public Connection getConnection(String username, String password) throws SQLException { return DriverManager.getConnection(props.getProperty("db.url"), username, password); diff --git a/src/main/java/model/DAO/DAOMessage.java b/src/main/java/model/DAO/DAOMessage.java index 731d814..8c29c7b 100644 --- a/src/main/java/model/DAO/DAOMessage.java +++ b/src/main/java/model/DAO/DAOMessage.java @@ -2,10 +2,7 @@ import model.entity.Message; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.*; public class DAOMessage { @@ -203,4 +200,37 @@ public int countReceivedMessages(int recipientId) { return count; } + + public void deleteLastInsertedMessage() { + Connection conn = null; + Statement stmt = null; + ResultSet rs = null; + + try { + conn = DAOConnection.getConnection(); + stmt = conn.createStatement(); + + String sql = "SELECT MAX(ID_message) FROM message"; + + rs = stmt.executeQuery(sql); + + if (rs.next()) { + int lastId = rs.getInt(1); + sql = "DELETE FROM message WHERE ID_message = " + lastId; + stmt.executeUpdate(sql); + } + + } catch (SQLException e) { + // Handle exceptions (e.g., print stack trace, log error, etc.) + e.printStackTrace(); + } finally { + try { + if (rs != null) rs.close(); + if (stmt != null) stmt.close(); + DAOConnection.releaseConnection(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/model/DAO/DAOUser.java b/src/main/java/model/DAO/DAOUser.java index ed611e0..295e72f 100644 --- a/src/main/java/model/DAO/DAOUser.java +++ b/src/main/java/model/DAO/DAOUser.java @@ -359,8 +359,6 @@ public boolean deleteUserByIdOrEmail(Object idOrEmail) { return rowsDeleted > 0; } catch (SQLException e) { - // Handle the exception (e.g., log or throw) - e.printStackTrace(); } finally { try { if (preparedStatement != null) preparedStatement.close(); diff --git a/src/test/java/model/DAO/DAOMessageTest.java b/src/test/java/model/DAO/DAOMessageTest.java index 85be589..3745f62 100644 --- a/src/test/java/model/DAO/DAOMessageTest.java +++ b/src/test/java/model/DAO/DAOMessageTest.java @@ -58,7 +58,7 @@ void testRetrieveMessages() { // Check the returned list assertNotNull(messages, "Returned list should not be null"); assertFalse(messages.isEmpty(), "Returned list should not be empty"); - assertNotEquals(0, messages.size()); // Assuming there are 2 messages between these users + assertNotEquals(0, messages.size()); // Assuming there are messages between these users } @Test @@ -83,9 +83,8 @@ void testSendMessage() { // Call the method to test daoMessage.sendMessage(senderId, recipientId, text); - - // Since the method doesn't return anything, we can't really verify its correctness - // However, we can assume it worked correctly if no exceptions were thrown + //clean it + daoMessage.deleteLastInsertedMessage(); } @Test diff --git a/src/test/java/model/service/license/LicenseActivationTest.java b/src/test/java/model/service/license/LicenseActivationTest.java index 1c8984c..fa27dba 100644 --- a/src/test/java/model/service/license/LicenseActivationTest.java +++ b/src/test/java/model/service/license/LicenseActivationTest.java @@ -71,24 +71,30 @@ void testIsForTherapist() { assertEquals(0, licenseActivation.isForTherapist(null)); } + @Test - void testActivate() { - // Mock the DAOLicense class - DAOLicense daoLicenseMock = mock(DAOLicense.class); + void testGeneratingLicenses(){ + DAOLicense daoLicense = new DAOLicense(); - // Set up the LicenseActivation class with the mocked DAO LicenseActivation licenseActivation = new LicenseActivation(); - licenseActivation.setDAOLicense(daoLicenseMock); + String licenseCode = licenseActivation.generateLicense(); + String pinCode = licenseActivation.generatePin(9); - // Create a sample license - License sampleLicense = new License(); - sampleLicense.setSequence("1234"); - sampleLicense.setIdUser(1); + assertEquals(8, licenseCode.length()); + assertEquals(4, pinCode.length()); + + licenseActivation.activate(daoLicense.getLicenseByCode(licenseCode), 0); + licenseActivation.activate(daoLicense.getLicenseByCode(pinCode), 999); + + License license1 = daoLicense.getLicenseByCode(licenseCode); + assertTrue(license1.isActive()); + assertEquals(0, license1.getIdUser()); - // Test the activate method - licenseActivation.activate(sampleLicense, 1); + License license2 = daoLicense.getLicenseByCode(pinCode); + assertTrue(license2.isActive()); + assertEquals(999, license2.getIdUser()); - // Verify that the DAO's activate method was called with the correct parameters - verify(daoLicenseMock, times(1)).activate(eq(sampleLicense), eq(1)); + daoLicense.deleteLicense(licenseCode); + daoLicense.deleteLicense(pinCode); } } diff --git a/src/test/java/model/service/user/UserDataTest.java b/src/test/java/model/service/user/UserDataTest.java new file mode 100644 index 0000000..d550c59 --- /dev/null +++ b/src/test/java/model/service/user/UserDataTest.java @@ -0,0 +1,78 @@ +package model.service.user; + + +import model.DAO.DAOUser; +import model.entity.User; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +public class UserDataTest { + + private UserData ud; + private int id; + @BeforeEach + void setup() { ud = new UserData(); } + + @Test + void createUser() { + // Arrange + String email = "unittest@example.com"; + String password = "password"; + int therapistId = 999; + if(ud.checkIfEmailExists("unittest@example.com")) { + new DAOUser().deleteUserByIdOrEmail("unittest@example.com"); + } + // Act + int result = ud.createUser(email, password, therapistId); + // Assert + assertTrue(result > 0, "The result should be positive"); + new DAOUser().deleteUserByIdOrEmail(id); + id = result; + } + + @Test + void checkIfEmailExists(){ + assertTrue(ud.checkIfEmailExists("doc1@example.com"), "this has been generated before, it must exists"); + } + + @Test + void getUser() { + User user = ud.getUser("doc1@example.com"); + assertNotNull(user, " User with email unittest@example.com must exist"); + if (user != null) + assertEquals("doc1@example.com", user.getEmail(), "Email should match"); + } + + @Test + void isTherapist() { + User user = new User(); + user.setIdTherapist(0); + boolean result = ud.isTherapist(user); + assertTrue(result, "User should be a therapist"); + + User user2 = new User(); + user.setIdTherapist(9); + boolean result2 = ud.isTherapist(user); + assertFalse(result2, "User should not be a therapist"); + } + + @Test + void updateAnalyticsPreference() { + + + String userId = Integer.toString(id); + boolean result = ud.updateAnalyticsPreference(userId, true); + assertTrue(result, "Analytics preference should be updated"); + } + + @Test + void updateEmailTime() { + String userId = Integer.toString(id); + boolean result = ud.updateEmailTime(userId, "11:00|12:00"); + assertTrue(result, "Email time should be updated"); + } + +}