Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#12048] Migrate tests for SessionLinksRecoveryAction #13281

Merged
merged 6 commits into from
Mar 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/main/java/teammates/sqllogic/api/Logic.java
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,13 @@ public Map<String, FeedbackQuestionRecipient> getRecipientsOfQuestion(
return feedbackQuestionsLogic.getRecipientsOfQuestion(question, instructorGiver, studentGiver, null);
}

/**
* Gets a list of students with the specified email.
*/
public List<Student> getAllStudentsForEmail(String email) {
return usersLogic.getAllStudentsForEmail(email);
}

/**
* Gets a feedbackResponse or null if it does not exist.
*/
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/teammates/ui/webapi/Action.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ public void setSqlEmailGenerator(SqlEmailGenerator sqlEmailGenerator) {
this.sqlEmailGenerator = sqlEmailGenerator;
}

public void setEmailGenerator(EmailGenerator emailGenerator) {
this.emailGenerator = emailGenerator;
}

/**
* Returns true if course has been migrated or does not exist in the datastore.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/test/java/teammates/sqlui/webapi/BaseActionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public abstract class BaseActionTest<T extends Action> extends BaseTestCase {
MockUserProvision mockUserProvision = new MockUserProvision();
teammates.logic.api.RecaptchaVerifier mockRecaptchaVerifier = mock(teammates.logic.api.RecaptchaVerifier.class);
SqlEmailGenerator mockSqlEmailGenerator = mock(SqlEmailGenerator.class);
teammates.logic.api.EmailGenerator mockEmailGenerator = mock(teammates.logic.api.EmailGenerator.class);
AuthProxy mockAuthProxy = mock(AuthProxy.class);

abstract String getActionUri();
Expand Down Expand Up @@ -112,6 +113,7 @@ protected T getAction(String body, List<Cookie> cookies, String... params) {
action.setUserProvision(mockUserProvision);
action.setRecaptchaVerifier(mockRecaptchaVerifier);
action.setSqlEmailGenerator(mockSqlEmailGenerator);
action.setEmailGenerator(mockEmailGenerator);
action.setAuthProxy(mockAuthProxy);
action.init(req);
return action;
Expand Down
30 changes: 27 additions & 3 deletions src/test/java/teammates/sqlui/webapi/CompileLogsActionTest.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package teammates.sqlui.webapi;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import java.time.Instant;
import java.util.HashMap;

import org.testng.annotations.Test;

import teammates.common.datatransfer.logs.GeneralLogEntry;
import teammates.common.datatransfer.logs.LogSeverity;
import teammates.common.datatransfer.logs.SourceLocation;
import teammates.common.util.Config;
import teammates.common.util.Const;
Expand Down Expand Up @@ -78,9 +84,27 @@ void testExecute_noRecentErrorLogs_noEmailSent() {

@Test
void testExecute_recentErrorLogs_emailSent() {
mockLogsProcessor.insertErrorLog("errorlogtrace1", "errorloginsertid1", sourceLocation,
RECENT_TIMESTAMP, "Error message 1", null);

GeneralLogEntry logEntry = new GeneralLogEntry(
LogSeverity.ERROR,
"errorlogtrace1",
"errorloginsertid1",
new HashMap<>(),
sourceLocation,
RECENT_TIMESTAMP
);
logEntry.setMessage("Error message 1");
logEntry.setDetails(null);

mockLogsProcessor.insertErrorLog(logEntry.getTrace(), logEntry.getInsertId(), logEntry.getSourceLocation(),
logEntry.getTimestamp(), logEntry.getMessage(), logEntry.getDetails());

EmailWrapper stubEmailWrapper;
stubEmailWrapper = new EmailWrapper();
stubEmailWrapper.setRecipient(Config.SUPPORT_EMAIL);
stubEmailWrapper.setSubject(String.format(EmailType.SEVERE_LOGS_COMPILATION.getSubject(), Config.APP_VERSION));

// use any() since the expected argument is a response from logs query
when(mockEmailGenerator.generateCompiledLogsEmail(any())).thenReturn(stubEmailWrapper);
CompileLogsAction action = getAction();
action.execute();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import org.testng.annotations.Test;

import teammates.common.util.Config;
import teammates.common.util.Const;
import teammates.common.util.EmailType;
import teammates.common.util.EmailWrapper;
Expand Down Expand Up @@ -44,6 +45,13 @@ void testExecute_typicalCase_success() {
Const.ParamsNames.USER_CAPTCHA_RESPONSE, USER_CAPTCHA_RESPONSE,
};

EmailWrapper stubEmailWrapper = new EmailWrapper();
stubEmailWrapper.setBcc(Config.SUPPORT_EMAIL);
stubEmailWrapper.setRecipient(USER_EMAIL);
stubEmailWrapper.setType(EmailType.LOGIN);
stubEmailWrapper.setSubjectFromType();
when(mockEmailGenerator.generateLoginEmail(USER_EMAIL, "http://localhost:4201")).thenReturn(stubEmailWrapper);

SendLoginEmailAction a = getAction(loginParams);
JsonResult result = getJsonResult(a);
SendLoginEmailResponseData output = (SendLoginEmailResponseData) result.getOutput();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package teammates.sqlui.webapi;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import teammates.common.datatransfer.attributes.CourseAttributes;
import teammates.common.datatransfer.attributes.StudentAttributes;
import teammates.common.util.Const;
import teammates.common.util.EmailWrapper;
import teammates.storage.sqlentity.Course;
import teammates.storage.sqlentity.Student;
import teammates.ui.output.SessionLinksRecoveryResponseData;
import teammates.ui.webapi.InvalidHttpParameterException;
import teammates.ui.webapi.JsonResult;
import teammates.ui.webapi.SessionLinksRecoveryAction;

/**
* SUT: {@link SessionLinksRecoveryAction}.
*/
public class SessionLinksRecoveryActionTest extends BaseActionTest<SessionLinksRecoveryAction> {
private Student stubStudent;
private Course stubCourse;
private EmailWrapper stubEmailWrapper;

@Override
protected String getActionUri() {
return Const.ResourceURIs.SESSION_LINKS_RECOVERY;
}

@Override
protected String getRequestMethod() {
return POST;
}

@BeforeMethod
void setUp() {
stubCourse = getTypicalCourse();
stubStudent = getTypicalStudent();
stubEmailWrapper = new EmailWrapper();
stubEmailWrapper.setRecipient(stubStudent.getEmail());
stubEmailWrapper.setSubject("TEAMMATES: Recovery Email");
reset(mockLogic, mockSqlEmailGenerator);
}

@Test
void testExecute_invalidEmailParam_throwsInvalidHttpParameterException() {
String[] params1 = {};
verifyHttpParameterFailure(params1);

String[] params2 = {
Const.ParamsNames.STUDENT_EMAIL, null,
};
verifyHttpParameterFailure(params2);

String[] params3 = {
Const.ParamsNames.STUDENT_EMAIL, "invalid-email-address",
};
InvalidHttpParameterException ihpe = verifyHttpParameterFailure(params3);
assertEquals("Invalid email address: invalid-email-address", ihpe.getMessage());
}

@Test
void testExecute_nonExistentEmail_success() {
String[] params = {
Const.ParamsNames.STUDENT_EMAIL, "non-existent@email.com",
Const.ParamsNames.USER_CAPTCHA_RESPONSE, "correct-captcha-response",
};

stubEmailWrapper.setRecipient("non-existent@email.com");
when(mockRecaptchaVerifier.isVerificationSuccessful(params[3])).thenReturn(true);
when(mockDatastoreLogic.getAllStudentsForEmail("non-existent@email.com")).thenReturn(List.of());
when(mockLogic.getAllStudentsForEmail("non-existent@email.com")).thenReturn(List.of());
when(mockSqlEmailGenerator.generateSessionLinksRecoveryEmailForStudent(
eq("non-existent@email.com"), eq(""), any()))
.thenReturn(stubEmailWrapper);
mockEmailSender.setShouldFail(false);

SessionLinksRecoveryAction action = getAction(params);
JsonResult result = getJsonResult(action);

SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput();
assertEquals("The recovery links for your feedback sessions have been sent to the "
+ "specified email address: non-existent@email.com", output.getMessage());
verifyNumberOfEmailsSent(1);
EmailWrapper emailSent = mockEmailSender.getEmailsSent().get(0);
assertEquals("TEAMMATES: Recovery Email", emailSent.getSubject());
assertEquals("non-existent@email.com", emailSent.getRecipient());
}

@Test
void testExecute_existingStudent_success() {
String[] params = {
Const.ParamsNames.STUDENT_EMAIL, stubStudent.getEmail(),
Const.ParamsNames.USER_CAPTCHA_RESPONSE, "correct-captcha-response",
};

when(mockRecaptchaVerifier.isVerificationSuccessful(params[3])).thenReturn(true);
StudentAttributes studentAttr = StudentAttributes.valueOf(stubStudent);
List<StudentAttributes> studentList = List.of(studentAttr);
when(mockDatastoreLogic.getAllStudentsForEmail(stubStudent.getEmail())).thenReturn(studentList);

Map<CourseAttributes, StringBuilder> linkFragmentsMap = new HashMap<>();
StringBuilder linkFragment = new StringBuilder("Test link fragment");
CourseAttributes courseAttr = CourseAttributes.builder(stubCourse.getId()).build();
linkFragmentsMap.put(courseAttr, linkFragment);
when(mockEmailGenerator.generateLinkFragmentsMap(studentList)).thenReturn(linkFragmentsMap);

when(mockSqlEmailGenerator.generateSessionLinksRecoveryEmailForStudent(
eq(stubStudent.getEmail()), eq(stubStudent.getName()), eq(linkFragmentsMap)))
.thenReturn(stubEmailWrapper);
mockEmailSender.setShouldFail(false);

SessionLinksRecoveryAction action = getAction(params);
JsonResult result = getJsonResult(action);

SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput();
assertTrue(output.isEmailSent());
assertEquals("The recovery links for your feedback sessions have been sent to the "
+ "specified email address: " + stubStudent.getEmail(), output.getMessage());

verifyNumberOfEmailsSent(1);
EmailWrapper emailSent = mockEmailSender.getEmailsSent().get(0);
assertEquals("TEAMMATES: Recovery Email", emailSent.getSubject());
assertEquals(stubStudent.getEmail(), emailSent.getRecipient());
}

@Test
void testExecute_captchaVerificationFailed_returnsFalseResponse() {
String[] params = {
Const.ParamsNames.STUDENT_EMAIL, stubStudent.getEmail(),
Const.ParamsNames.USER_CAPTCHA_RESPONSE, "incorrect-captcha-response",
};

when(mockRecaptchaVerifier.isVerificationSuccessful(params[3])).thenReturn(false);

SessionLinksRecoveryAction action = getAction(params);
JsonResult result = getJsonResult(action);

SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput();
assertFalse(output.isEmailSent());
assertEquals("Something went wrong with the reCAPTCHA verification. Please try again.",
output.getMessage());

verifyNoEmailsSent();
}

@Test
void testExecute_emailSendingFails_returnsFalseResponse() {
String[] params = {
Const.ParamsNames.STUDENT_EMAIL, stubStudent.getEmail(),
Const.ParamsNames.USER_CAPTCHA_RESPONSE, "correct-captcha-response",
};

when(mockRecaptchaVerifier.isVerificationSuccessful(params[3])).thenReturn(true);
StudentAttributes studentAttr = StudentAttributes.valueOf(stubStudent);
List<StudentAttributes> studentList = List.of(studentAttr);
when(mockDatastoreLogic.getAllStudentsForEmail(stubStudent.getEmail())).thenReturn(studentList);

Map<CourseAttributes, StringBuilder> linkFragmentsMap = new HashMap<>();
StringBuilder linkFragment = new StringBuilder("Test link fragment");
CourseAttributes courseAttr = CourseAttributes.builder(stubCourse.getId()).build();
linkFragmentsMap.put(courseAttr, linkFragment);
when(mockEmailGenerator.generateLinkFragmentsMap(studentList)).thenReturn(linkFragmentsMap);

when(mockSqlEmailGenerator.generateSessionLinksRecoveryEmailForStudent(
eq(stubStudent.getEmail()), eq(stubStudent.getName()), eq(linkFragmentsMap)))
.thenReturn(stubEmailWrapper);
mockEmailSender.setShouldFail(true);

SessionLinksRecoveryAction action = getAction(params);
JsonResult result = getJsonResult(action);

SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput();
assertFalse(output.isEmailSent());
assertEquals("An error occurred. The email could not be sent.", output.getMessage());
}

@Test
protected void testAccessControl() {
verifyCanAccess();
}
}
Loading